def Commands_operator(uname, command): commandobj = config['Commands'].get(command) if commandobj != None and Users.get( Query().name == uname).get('Coins') > commandobj.get('cost'): if commandobj.get('type') == 'sk': #SendKeys if 'active' in state and commandobj.get('state') == 'multiple': state.clear() key_value_up = '{{{} up}}'.format(commandobj.get('value')) send_keys(key_value_up) elif commandobj.get('state') == 'multiple': state.append('active') key_value_down = '{{{} down}}'.format(commandobj.get('value')) send_keys(key_value_down) else: key_value = '{{{}}}'.format(commandobj.get('value')) send_keys(key_value) Users.update(subtract('Coins', commandobj.get('cost')), Query().name == uname) return elif commandobj.get('type') == 'ws': #Playsound sound = AudioSegment.from_file('./sounds/' + commandobj.get('file')).apply_gain( commandobj.get('volume')) play(sound) Users.update(subtract('Coins', commandobj.get('cost')), Query().name == uname) return return
async def take_coin(userid, coin_value=0.1): db = TinyDB('db.json') cursor = Query() if user_exists(userid): db.update(subtract("wallet", coin_value), cursor.userid == userid) else: db.insert({"userid": userid, "wallet": coin_value})
def buy_stock(account, clip): # deduct the cost db.update(subtract('bucks', STOCK_COST), (where('type') == 'account') & (where('id') == account['id'])) # purchase the stock if len( db.update(increment('shares'), (where('type') == 'stock') & (where('clip') == clip) & (where('user_id') == account['id']))) == 0: db.insert({ 'type': 'stock', 'user_id': account['id'], 'disp_name': account['name'], 'clip': clip, 'shares': 1, 'total_payout': 0 })
def new_wager(disp_name, account, amount, clip, count): # deduct amount db.update(subtract('bucks', amount), (where('type') == 'account') & (where('id') == account['id'])) # update display name if needed db.update(set('name', disp_name), (where('type') == 'account') & (where('id') == account['id'])) # place wager db.insert({ 'type': 'wager', 'wager_id': str(uuid.uuid4()), 'user_id': account['id'], 'disp_name': disp_name, 'clip': clip, 'amount': amount, 'count': count, 'start_count': count })
def add_tip(amt, account, send_to_id=None): # deduct amount db.update(subtract('bucks', amt), (where('type') == 'account') & (where('id') == account['id'])) if len( db.update(add('total', amt), (where('type') == 'usertips') & (where('id') == account['id']))) == 0: db.insert({ 'type': 'usertips', 'total': amt, 'id': account['id'], 'name': account["name"] }) if send_to_id is not None: db.update(add('bucks', amt), (where('type') == 'account') & (where('id') == send_to_id)) elif len(db.update(add('total', amt), (where('type') == 'tips'))) == 0: db.insert({'type': 'tips', 'total': amt}) else: result = db.get(where('type') == 'tips') return result
def my_del(self, cmdr, user, amount): if not user or not amount: self.errlog_add( "No \"client\" ({}) or \"amount\" ({}) given!".format( user, amount)) return # handle DB entry try: self.db_action.insert({ 'issuer': cmdr.id, 'user': user.id, 'action': 'delete', 'amount': amount, 'when': datetime.now().timetuple() }) query = Query() if self.db_lending.contains(query.id == user.id): self.db_lending.update(subtract('borrowed', amount), query.id == user.id) else: self.errlog_add( "User {} never borrowed any Excavators. Ignored!".format( user.name)) return if self.db_lending.contains((query.id == user.id) & (query.borrowed <= 0)): self.db_lending.remove(query.id == user.id) logger.info("{} handed back from {} {} Excavators".format( cmdr, user, amount)) result = self.db_lending.get(query.id == user.id) if len(result) == 0: result['borrowed'] = 0 self.errlog_add( "{} returned **{}** Excavators. He now has **{}**".format( user.name, amount, result['borrowed'])) except Exception as e: logger.error("Error occurred: {}".format(e), exc_info=True)
def remove_tacos(self, amount): users_db.update(subtract('daily_tacos', amount), Query()['user_id'] == self.user_id) self.update()
def test_subtract(db): db.update(subtract('int', 5), where('char') == 'a') assert db.get(where('char') == 'a')['int'] == -4
async def reactionRemoved(bot, payload): if payload.guild_id is None: return User = Query() userid = payload.user_id # Misc. definitions. # Attempt a get_x command for brevity. If that doesn't work, use fetch_x (slow). user = bot.get_user(payload.user_id) if not user: user = await bot.fetch_user(payload.user_id) print("User not found. Trying to fetch it...") channel = bot.get_channel(payload.channel_id) if not channel: channel = await bot.fetch_channel(payload.channel_id) print("Channel not found. Trying to fetch it...") guild = bot.get_guild(payload.guild_id) if not guild: guild = await bot.fetch_guild(payload.guild_id) print("Guild not found. Trying to fetch it...") member = guild.get_member(payload.user_id) if not member: member = await guild.fetch_member(payload.user_id) print("Member not found. Trying to fetch it...") # no such thing as "get_message" message = await channel.fetch_message(payload.message_id) if ((userid != message.author.id) or (debug == True)) and not user.bot: if not isinstance(payload.emoji, str): channel = message.channel removable = None if payload.emoji.name == '10': # the bot auto-removes stars given out by non-curators. # if this is from a non-curator, ignore all this code! otherwise we're just removing points without adding them first. if discord.utils.get(member.roles, name="Curator") is None: return removable = 10 if payload.emoji.name == 'plus': removable = 1 if payload.emoji.name == 'minus': removable = -1 if removable: # Remove the user's karma. value = message.author.id exists = db.count(Query().username == str(value)) if not (exists == 0): db.update(subtract('points', removable), where('username') == str(value)) # Remove the comment's karma. valuetwo = str(message.id) postexists = post.count(Query().msgid == str(valuetwo)) if not (postexists == 0): post.update(subtract('points', removable), where('msgid') == str(valuetwo)) #post.update(subtract('voters',[user.id]), where('msgid') == str(valuetwo)) if payload.emoji.name == '10': post.update(subtract('stars', 1), where('msgid') == str(valuetwo)) # todo (if possible): remove the message from the best of channel if there are 0 :10: reactions # we shouldn't send a message if someone un-reacted, that'd be mean. # instead, we send a reaction unless notifications are disabled server = str(message.guild.id) checkM = bot.get_emoji(660217963911184384) notifmode = best.search(Query().serverid == server) notifmode = notifmode[0]['notification'] if notifmode != "disabled": react = await message.add_reaction(checkM) await asyncio.sleep(1) botid = bot.user await message.remove_reaction(checkM, botid)
def give_tacos(giving_user, receiv_user, n_tacos, reaction=False, channel=None): user = Query() init_user(giving_user) init_user(receiv_user) giving_owned_tacos = db.search( user.user_id == giving_user)[0]['daily_tacos'] if giving_owned_tacos - n_tacos >= 0: db.update(add('owned_tacos', n_tacos), user.user_id == receiv_user) db.update(subtract('daily_tacos', n_tacos), user.user_id == giving_user) # LOG to DB db_logs.insert({ 'giving_user': giving_user, 'receiver_user': receiv_user, 'n_tacos': n_tacos, 'type': 'reaction' if reaction else 'message', 'date': today }) slack_client.api_call( "chat.postMessage", channel=giving_user, as_user=True, text="¡<@" + receiv_user + "> *ha recibido {0:g} x :taco:* de tu parte! Te quedan {1:g} tacos para repartir hoy." .format( n_tacos, db.search( Query()['user_id'] == giving_user)[0]['daily_tacos'])) owned_tacos = db.search( Query().user_id == receiv_user)[0]['owned_tacos'] slack_client.api_call( "chat.postMessage", channel=receiv_user, as_user=True, text=("¡*Has recibido {0:g} x :taco: * de <@" + giving_user + "> en el canal <#" + channel + ">! Ya tienes *{1:g}x :taco: ").format(n_tacos, owned_tacos)) else: slack_client.api_call( "chat.postMessage", channel=giving_user, as_user=True, text= "*¡No tienes suficientes tacos!* Recibirás {0:g} TACOS NUEVOS :taco: recién cocinados en *{1:} horas.*" .format(DAILY_TACOS, time_left)) # To-do: Send giving user private message : No more tacos! You have to wait... {Time} return None
async def joinbr(self, context): """Joins the battle royale with an entry fee.""" BaseCog.check_main_server(self, context) BaseCog.check_bot_channel(self, context) BaseCog.check_forbidden_characters(self, context) await BaseCog.dynamic_user_add(self, context) economy = BaseCog.load_dependency(self, 'Economy') main_db = economy.main_db stats = BaseCog.load_dependency(self, 'Stats') trivia_table = stats.trivia_table gambling = BaseCog.load_dependency(self, 'Gambling') weapon_emotes = gambling.weapon_emotes is_participating = context.message.author.name in self.br_participants try: pukcab_pool = self.br_pool if self.br_closed: await self.bot.post_error(context, 'You are too late to join the recent battle royale, ' + context.message.author.name + '. Start a new one with !battleroyale <bet> if you are so eager to fight.') elif context.message.author.name in self.br_participants: await self.bot.post_error(context, 'You are already taking part in this battle royale, ' + context.message.author.name + '.') else: user_balance = main_db.get(self.bot.query.user == context.message.author.name)['balance'] # Check if battle royale is today's minigame for holiday points holidays = self.bot.get_cog('Holidays') is_holiday_minigame = False holiday = 0 if holidays is not None: if holidays.holiday_minigame.contains(self.bot.query.minigame == 'Battle Royale'): is_holiday_minigame = True holiday = main_db.get(self.bot.query.user == context.message.author.name)['holiday'] if user_balance + holiday >= self.br_bet: self.br_participants.append(context.message.author.name) self.br_pool += self.br_bet # Remove entry fee if holiday > 0: leftover = self.br_bet - holiday if leftover > 0: # i.e. br bet > holiday points main_db.update(subtract('holiday', holiday), self.bot.query.user == context.message.author.name) self.br_holiday_points_used.append(holiday) main_db.update(subtract('balance', leftover), self.bot.query.user == context.message.author.name) main_db.update(subtract('gambling_profit', leftover), self.bot.query.user == context.message.author.name) else: # Note: holiday points do not count as negative gambling profit main_db.update(subtract('holiday', self.br_bet), self.bot.query.user == context.message.author.name) self.br_holiday_points_used.append(self.br_bet) else: main_db.update(subtract('balance', self.br_bet), self.bot.query.user == context.message.author.name) main_db.update(subtract('gambling_profit', self.br_bet), self.bot.query.user == context.message.author.name) self.br_holiday_points_used.append(0) await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** ' + context.message.author.name + ' has joined the challengers! The prize pool is now at ' + str(self.br_pool) + ' ' + config.currency_name + 's.') else: await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** You do not have enough ' + config.currency_name + 's, ' + context.message.author.name + '. The entry fee is ' + str(self.br_bet) + ' ' + config.currency_name + 's and your current balance is ' + str(user_balance) + '.') except Exception as e: try: if (context.message.author.name in self.br_participants) and not is_participating: self.br_participants.pop() # Careful: We might have crashed before even adding the used holiday points, so can't always pop! if len(self.br_participants) < len(self.br_holiday_points_used): self.br_holiday_points_used.pop() self.br_pool = pukcab_pool await self.bot.post_error(context, 'Oh no, something went wrong (you are not part of the challengers).', config.additional_error_message) log.exception(e) except Exception as e2: await self.bot.post_error(context, 'Oh no, something went wrong (you are not part of the challengers).', config.additional_error_message) log.exception(e2)
async def rosebud(self, ctx, *args): """[BOT ADMIN ONLY] Add or subtract karma from an user.""" prefix = await getCurrentPrefix(ctx) isOwner = False for x in botowner: if (int(ctx.message.author.id) == int(x)): isOwner = True if isOwner: if not args: await sendErrorEmbed( ctx, "Hey! You should probably tag someone first.\nIntended usage: " + prefix + "rosebud `[user]` `[amount of karma]` `[add/subtract]`") return if not ctx.message.mentions: await sendErrorEmbed(ctx, "You forgot to add in an user!") return else: user = ctx.message.mentions[0] if len(args) < 2: await sendErrorEmbed( ctx, "You haven't entered a karma amount!") return if args[1].isdigit(): karma = int(args[1]) value = "" if len(args) < 3: await sendErrorEmbed( ctx, "You have to enter an argument! `[add/subtract]`") return if args[2] == "add": value = "add" elif args[2] == "subtract": value = "subtract" else: await sendErrorEmbed( ctx, "That's not a valid argument! `[add/subtract]`") return if args[2] and value: # DO THE THING exists = db.count(Query().username == str(user.id)) server = str(ctx.message.guild.id) if exists == 0: if value == "add": db.insert({ 'username': str(user.id), 'points': karma, 'servers': [server] }) if value == "subtract": db.insert({ 'username': str(user.id), 'points': -karma, 'servers': [server] }) else: if value == "add": db.update(add('points', karma), where('username') == str(user.id)) if value == "subtract": db.update(subtract('points', karma), where('username') == str(user.id)) result = db.get(Query()['username'] == str(user.id)) await ctx.send('Great! ' + user.name + "'s new karma total is " + str(result.get('points')) + ".") else: await sendErrorEmbed( ctx, "That's not a valid amount of karma!") return else: await sendErrorEmbed( ctx, "Looks like you don't have permission to do this?\n_Are you hosting " + botname + "? If so make sure your User ID is on the **botowner** array on the config.json file!_" )
async def reactionAdded(bot, payload): if payload.guild_id is None: return User = Query() userid = payload.user_id # Misc. definitions. # Attempt a get_x command for brevity. If that doesn't work, use fetch_x (slow). user = bot.get_user(payload.user_id) if not user: user = await bot.fetch_user(payload.user_id) print("User not found. Trying to fetch it...") channel = bot.get_channel(payload.channel_id) if not channel: channel = await bot.fetch_channel(payload.channel_id) print("Channel not found. Trying to fetch it...") guild = bot.get_guild(payload.guild_id) if not guild: guild = await bot.fetch_guild(payload.guild_id) print("Guild not found. Trying to fetch it...") member = guild.get_member(payload.user_id) if not member: member = await guild.fetch_member(payload.user_id) print("Member not found. Trying to fetch it...") # no such thing as "get_message" message = await channel.fetch_message(payload.message_id) if ((userid != message.author.id) or (debug == True)) and not user.bot: if not isinstance(payload.emoji, str): # ------------------------- # REACTION = :10: # ------------------------- channel = message.channel is_nsfw = channel.is_nsfw() if payload.emoji.name == '10': if discord.utils.get(member.roles, name="Curator") is None: await message.remove_reaction(payload.emoji, user) else: channel = message.channel messageurl = "https://discordapp.com/channels/" + str( message.guild.id) + "/" + str( message.channel.id) + "/" + str(message.id) # Post the message in #best-of contenido = message.content autor = message.author.name foto = message.author.avatar_url if (len(message.attachments) > 0): imagen = message.attachments[0].url color = "" # If there's an embed, set the color of the new embed to it. (first come, first serve) if (message.embeds): embed = message.embeds[0].to_dict() if "color" in embed: color = embed['color'] if color: emberino = discord.Embed(description=contenido, color=color) else: emberino = discord.Embed(description=contenido) emberino.set_author(name=autor, url=messageurl, icon_url=foto) if (len(message.attachments) > 0): emberino.set_image(url=imagen) # Parsing embeds: if (message.embeds): for embed in message.embeds: embed = embed.to_dict() thisEmbed = emberino.to_dict() if (len(message.attachments) == 0) and not "image" in thisEmbed: if "thumbnail" in embed: emberino.set_image( url=embed['thumbnail']['url']) if "image" in embed: emberino.set_image( url=embed['image']['url']) if not "footer" in thisEmbed: if "footer" in embed: emberino.set_footer( text=embed['footer']['text']) else: footer = "" if "provider" in embed: footer = embed['provider']['name'] if "author" in embed and not "title" in embed: footer = embed['author']['name'] if footer: emberino.set_footer(text=footer) title = "" description = "" if "title" in embed: title = embed['title'] elif "author" in embed: title = embed['author']['name'] if "description" in embed: description = embed['description'] if title and description: emberino.add_field(name=title, value=description, inline=False) if "fields" in embed: for field in embed["fields"]: emberino.add_field(name=field['name'], value=field['value'], inline=False) # the difficult challenge of finding the channel to post to best.clear_cache() server = str(message.guild.id) channel = best.search(Query().serverid == server) valuetwo = str(message.id) postexists = post.search(Query().msgid == valuetwo) if postexists: postexists = int(postexists[0]['stars']) else: postexists = 0 if (postexists == 0): try: channel = channel[0][ 'channelid'] # channel id of best-of channel channel = discord.utils.get(message.guild.channels, id=channel) if channel == None: channel = discord.utils.get( message.guild.channels, name="best-of") if channel == None: # if the bot doesn't find a channel named best-of, the channnel has been deleted. create a new one! await message.guild.create_text_channel( 'best-of') channel = discord.utils.get( message.guild.channels, name="best-of") best.upsert( { 'serverid': server, 'channelid': channel.id, 'notification': "message" }, Query().serverid == server) channelformsg = message.channel await channelformsg.send( "The *Best Of* channel doesn't exist, if the bot has permissions it has been created." ) channel = best.search( Query().serverid == server) channel = channel[0]['channelid'] channel = discord.utils.get( message.guild.channels, id=channel) else: # if the bot does find a channel named best-of, the channel needs to be linked to the new db. # this is for legacy users (1.3.5 and below) best.upsert( { 'serverid': server, 'channelid': channel.id, 'notification': "message" }, Query().serverid == server) channel = best.search( Query().serverid == server) channel = channel[0]['channelid'] channel = discord.utils.get( message.guild.channels, id=channel) except IndexError: channel = discord.utils.get(message.guild.channels, name="best-of") if channel == None: # if the bot doesn't find a channel named best-of, the channnel has been deleted. create a new one! await message.guild.create_text_channel( 'best-of') channel = discord.utils.get( message.guild.channels, name="best-of") best.upsert( { 'serverid': server, 'channelid': channel.id, 'notification': "message" }, Query().serverid == server) channelformsg = message.channel await channelformsg.send( "The *Best Of* channel doesn't exist, if the bot has permissions it has been created." ) channel = best.search( Query().serverid == server) channel = channel[0]['channelid'] channel = discord.utils.get( message.guild.channels, id=channel) else: # if the bot does find a channel named best-of, the channel needs to be linked to the new db. # this is for legacy users (1.3.5 and below) best.upsert( { 'serverid': server, 'channelid': channel.id, 'notification': "message" }, Query().serverid == server) channel = best.search( Query().serverid == server) channel = channel[0]['channelid'] channel = discord.utils.get( message.guild.channels, id=channel) # Add user to the points table value = str(message.author.id) exists = db.count(Query().username == value) server = str(message.guild.id) if exists == 0: db.insert({ 'username': value, 'points': 10, 'servers': [server] }) else: User = Query() serverid = str(message.guild.id) existsserver = db.count( (User.servers.any([serverid])) & (User.username == value)) # no funciona if existsserver == 0: db.update(add('points', 10), where('username') == value) l = str(db.search((User.username == value))) if "servers" not in l: docs = db.search(User.username == value) for doc in docs: doc['servers'] = [str(server)] db.write_back(docs) else: db.update(add('servers', [server]), where('username') == value) else: db.update(add('points', 10), where('username') == value) # Finally, the bot sends the message to the Best-Of channel. if channel == None: channelformsg = message.channel await sendErrorEmbed( channelformsg, "The channel couldn't be sent to the Best Of channel, for some reason. Could you double-check it exists?" ) else: if (postexists == 0): await channel.send(embed=emberino) # Log post for post leaderboard priv.clear_cache() privSettings = priv.search( Query().username == message.author.id) if privSettings: privSettings = privSettings[0] username = str(message.author.id) notifmode = best.search(Query().serverid == server) notifmode = notifmode[0]['notification'] # ISO 8601! curdate = str(datetime.now()) if postexists == 0: if not privSettings or "mode" in privSettings and privSettings[ 'mode'] == False or not "mode" in privSettings: attachments = "" if (len(message.attachments) > 0): attachments = message.attachments[0].url if (message.embeds): richembeds = [None] * len(message.embeds) i = 0 for embed in message.embeds: richembeds[i] = embed.to_dict() i = i + 1 else: richembeds = "" post.insert({ 'msgid': valuetwo, 'username': username, 'points': 10, 'servers': server, 'content': message.content, 'embed': attachments, 'richembed': richembeds, 'voters': [user.id], 'stars': 1, 'nsfw': is_nsfw, 'timestamp': curdate }) else: print("Privacy Mode ENABLED!") else: post.update(add('points', 10), where('msgid') == valuetwo) post.update(add('voters', [user.id]), where('msgid') == valuetwo) post.update(add('stars', 1), where('msgid') == valuetwo) if (notifmode != "reaction") and (notifmode != "disabled"): channel = message.channel result = db.get(Query()['username'] == value) send = await channel.send( "Huzzah! **{}**'s post was so good it got starred more than once. They now have {} points. (+10)" .format(message.author.name, result.get('points'))) # Send a confirmation message channel = message.channel result = db.get(Query()['username'] == value) bestofname = best.search(Query().serverid == server) bestofname = bestofname[0]['channelid'] bestofname = discord.utils.get(message.guild.channels, id=bestofname) checkM = bot.get_emoji(660217963911184384) if notifmode == "reaction": react = await message.add_reaction(checkM) if (notifmode != "reaction") and ( notifmode != "disabled") and (postexists == 0): send = await channel.send( "Congrats, **{}**! Your post will be forever immortalized in the **#{}** channel. You now have {} points. (+10)" .format(message.author.name, bestofname.name, result.get('points'))) # Delete said message if notifmode == "reaction": await asyncio.sleep(1) botid = bot.user await message.remove_reaction(checkM, botid) if (notifmode != "reaction") and (notifmode != "disabled"): await asyncio.sleep(3) await send.delete() # ------------------------- # REACTION = :PLUS: # ------------------------- if payload.emoji.name == 'plus': channel = message.channel # Add user to the points table value = str(message.author.id) exists = db.count(Query().username == value) server = str(message.guild.id) if exists == 0: db.insert({ 'username': value, 'points': 1, 'servers': [server] }) # Send a confirmation message or reaction notifmode = best.search(Query().serverid == server) notifmode = notifmode[0]['notification'] checkM = bot.get_emoji(660217963911184384) if notifmode == "reaction": react = await message.add_reaction(checkM) if (notifmode != "reaction") and (notifmode != "disabled"): result = db.get(Query()['username'] == value) heart = await channel.send( "**Hearted!** {} now has {} points. (+1)".format( message.author.name, result.get('points'))) if notifmode == "reaction": await asyncio.sleep(1) botid = bot.user await message.remove_reaction(checkM, botid) if (notifmode != "reaction") and (notifmode != "disabled"): await asyncio.sleep(3) await heart.delete() else: User = Query() serverid = str(message.guild.id) existsserver = db.count( (User.servers.any([serverid])) & (User.username == value)) # no funciona print(str(existsserver)) if existsserver == 0: db.update(add('points', 1), where('username') == value) l = str(db.search((User.username == value))) print(l) if "servers" not in l: docs = db.search(User.username == value) for doc in docs: doc['servers'] = [str(server)] db.write_back(docs) else: db.update(add('servers', [server]), where('username') == value) else: db.update(add('points', 1), where('username') == value) # Log post for post leaderboard priv.clear_cache() privSettings = priv.search( Query().username == message.author.id) if privSettings: privSettings = privSettings[0] valuetwo = str(message.id) username = str(message.author.id) postexists = post.count(Query().msgid == valuetwo) # ISO 8601! curdate = str(datetime.now()) if postexists == 0: if not privSettings or "mode" in privSettings and privSettings[ 'mode'] == False or not "mode" in privSettings: attachments = "" if (len(message.attachments) > 0): attachments = message.attachments[0].url if (message.embeds): richembeds = [None] * len(message.embeds) i = 0 for embed in message.embeds: richembeds[i] = embed.to_dict() i = i + 1 else: richembeds = "" post.insert({ 'msgid': valuetwo, 'username': username, 'points': 1, 'servers': server, 'content': message.content, 'embed': attachments, 'richembed': richembeds, 'voters': [user.id], 'stars': 0, 'nsfw': is_nsfw, 'timestamp': curdate }) else: print("Privacy Mode ENABLED!") else: post.update(add('points', 1), where('msgid') == valuetwo) post.update(add('voters', [user.id]), where('msgid') == valuetwo) best.clear_cache() notifmode = best.search(Query().serverid == server) notifmode = notifmode[0]['notification'] checkM = bot.get_emoji(660217963911184384) if notifmode == "reaction": react = await message.add_reaction(checkM) if (notifmode != "reaction") and (notifmode != "disabled"): result = db.get(Query()['username'] == value) heart = await channel.send( "**Hearted!** {} now has {} points. (+1)".format( message.author.name, result.get('points'))) # Delete said message if notifmode == "reaction": await asyncio.sleep(1) botid = bot.user await message.remove_reaction(checkM, botid) if (notifmode != "reaction") and (notifmode != "disabled"): await asyncio.sleep(3) await heart.delete() # ------------------------- # REACTION = :MINUS: # ------------------------- if payload.emoji.name == 'minus': channel = message.channel # Add user to the points table value = str(message.author.id) exists = db.count(Query().username == value) server = str(message.guild.id) if exists == 0: db.insert({ 'username': value, 'points': -1, 'servers': [server] }) # Send a confirmation message notifmode = best.search(Query().serverid == server) notifmode = notifmode[0]['notification'] checkM = bot.get_emoji(660217963911184384) if notifmode == "reaction": react = await message.add_reaction(checkM) if (notifmode != "reaction") and (notifmode != "disabled"): result = db.get(Query()['username'] == value) crush = await channel.send( "**Crushed.** {} now has {} points. (-1)".format( message.author.name, result.get('points'))) if notifmode == "reaction": await asyncio.sleep(1) botid = bot.user await message.remove_reaction(checkM, botid) if (notifmode != "reaction") and (notifmode != "disabled"): await asyncio.sleep(3) await crush.delete() else: User = Query() serverid = str(message.guild.id) existsserver = db.count( (User.servers.any([serverid])) & (User.username == value)) # no funciona print(str(existsserver)) if existsserver == 0: db.update(subtract('points', 1), where('username') == value) l = str(db.search((User.username == value))) print(l) if "servers" not in l: docs = db.search(User.username == value) for doc in docs: doc['servers'] = [str(server)] db.write_back(docs) else: db.update(add('servers', [server]), where('username') == value) else: db.update(subtract('points', 1), where('username') == value) # Log post for post leaderboard priv.clear_cache() privSettings = priv.search( Query().username == message.author.id) if privSettings: privSettings = privSettings[0] valuetwo = str(message.id) username = str(message.author.id) postexists = post.count(Query().msgid == valuetwo) # ISO 8601! curdate = str(datetime.now()) if postexists == 0: if not privSettings or "mode" in privSettings and privSettings[ 'mode'] == False or not "mode" in privSettings: attachments = "" if (len(message.attachments) > 0): attachments = message.attachments[0].url if (message.embeds): richembeds = [None] * len(message.embeds) i = 0 for embed in message.embeds: richembeds[i] = embed.to_dict() i = i + 1 else: richembeds = "" post.insert({ 'msgid': valuetwo, 'username': username, 'points': -1, 'servers': server, 'content': message.content, 'embed': attachments, 'richembed': richembeds, 'voters': [user.id], 'stars': 0, 'nsfw': is_nsfw, 'timestamp': curdate }) else: print("Privacy Mode ENABLED!") else: post.update(subtract('points', 1), where('msgid') == valuetwo) post.update(add('voters', [user.id]), where('msgid') == valuetwo) # Send a confirmation message best.clear_cache() notifmode = best.search(Query().serverid == server) notifmode = notifmode[0]['notification'] checkM = bot.get_emoji(660217963911184384) if notifmode == "reaction": react = await message.add_reaction(checkM) if (notifmode != "reaction") and (notifmode != "disabled"): result = db.get(Query()['username'] == value) crush = await channel.send( "**Crushed.** {} now has {} points. (-1)".format( message.author.name, result.get('points'))) # Delete said message if notifmode == "reaction": await asyncio.sleep(1) botid = bot.user await message.remove_reaction(checkM, botid) if (notifmode != "reaction") and (notifmode != "disabled"): await asyncio.sleep(3) await crush.delete()
async def on_reaction_add(self, reaction, user): if (2 + 2) == 4: # remove when testing! # ------------------------- # REACTION = :10: # ------------------------- if reaction.emoji.name == '10' and reaction.count == 1: channel = reaction.message.channel messageurl = "https://discordapp.com/channels/" + str( reaction.message.guild.id) + "/" + str( reaction.message.channel.id) + "/" + str( reaction.message.id) # Post the message in #best-of contenido = reaction.message.content autor = reaction.message.author.name foto = reaction.message.author.avatar_url if (len(reaction.message.attachments) > 0): imagen = reaction.message.attachments[0].url subido = reaction.users(limit=1) emberino = discord.Embed(description=contenido) emberino.set_author(name=autor, url=messageurl, icon_url=foto) if (len(reaction.message.attachments) > 0): emberino.set_image(url=imagen) channel = discord.utils.get(reaction.message.guild.channels, name="best-of") # Add user to the points table value = str(reaction.message.author.id) exists = db.count(Query().username == value) server = str(reaction.message.guild.id) if exists == 0: print("user didnt exist.") db.insert({ 'username': value, 'points': 10, 'servers': [server] }) else: User = Query() serverid = str(reaction.message.guild.id) existsserver = db.count( (User.servers.any([serverid])) & (User.username == value)) # no funciona print(str(existsserver)) print("user does exist.") print("server id: " + serverid) print("is the server in the list?? = " + str(existsserver)) if existsserver == 0: print("server wasnt on the list.") db.update(add('points', 10), where('username') == value) l = str(db.search((User.username == value))) print(l) if "servers" not in l: print( "legacy user, didn't have any servers. added its first one" ) docs = db.search(User.username == value) for doc in docs: doc['servers'] = [str(server)] db.write_back(docs) else: print("added a new server!") db.update(add('servers', [server]), where('username') == value) else: print("server was on the list.") db.update(add('points', 10), where('username') == value) # If the channel #best-of doesn't exist, the bot creates it before posting it. if channel == None: await reaction.message.guild.create_text_channel('best-of') channel = reaction.message.channel await channel.send( "The channel **best-of** doesn't exist, if the bot has permissions it has been created." ) channel = discord.utils.get( reaction.message.guild.channels, name="best-of") await channel.send(embed=emberino) else: await channel.send(embed=emberino) # Log post for post leaderboard priv.clear_cache() exists = priv.count( Query().username == reaction.message.author.id) valuetwo = str(reaction.message.id) username = str(reaction.message.author.id) postexists = post.count(Query().msgid == valuetwo) if postexists == 0: if exists == 0: print("post wasnt previously on lb") if (len(reaction.message.attachments) > 0): post.insert({ 'msgid': valuetwo, 'username': username, 'points': 10, 'servers': server, 'content': reaction.message.content, 'embed': reaction.message.attachments[0].url }) else: post.insert({ 'msgid': valuetwo, 'username': username, 'points': 10, 'servers': server, 'content': reaction.message.content, 'embed': '' }) else: print("user has privacy mode on") else: print("post was previously on db") post.update(add('points', 10), where('msgid') == valuetwo) # Send a confirmation message channel = reaction.message.channel result = db.get(Query()['username'] == value) send = await channel.send( "Congrats, **{}**! Your post will be forever immortalized in the server's #best-of. You now have {} points. (+10)" .format(reaction.message.author.name, result.get('points'))) # Delete said message await asyncio.sleep(3) await send.delete() # ------------------------- # REACTION = :PLUS: # ------------------------- if reaction.emoji.name == 'plus': channel = reaction.message.channel # Add user to the points table value = str(reaction.message.author.id) exists = db.count(Query().username == value) server = str(reaction.message.guild.id) if exists == 0: print("user didnt exist.") db.insert({ 'username': value, 'points': 1, 'servers': [server] }) # Send a confirmation message result = db.get(Query()['username'] == value) heart = await channel.send( "**Hearted!** {} now has {} points. (+1)".format( reaction.message.author.name, result.get('points'))) await asyncio.sleep(3) await heart.delete() else: User = Query() serverid = str(reaction.message.guild.id) existsserver = db.count( (User.servers.any([serverid])) & (User.username == value)) # no funciona print(str(existsserver)) print("user does exist.") print("server id: " + serverid) print("is the server in the list?? = " + str(existsserver)) if existsserver == 0: print("server wasnt on the list.") db.update(add('points', 1), where('username') == value) l = str(db.search((User.username == value))) print(l) if "servers" not in l: print( "legacy user, didn't have any servers. added its first one" ) docs = db.search(User.username == value) for doc in docs: doc['servers'] = [str(server)] db.write_back(docs) else: print("added a new server!") db.update(add('servers', [server]), where('username') == value) else: print("server was on the list.") db.update(add('points', 1), where('username') == value) # Log post for post leaderboard priv.clear_cache() exists = priv.count( Query().username == reaction.message.author.id) valuetwo = str(reaction.message.id) username = str(reaction.message.author.id) postexists = post.count(Query().msgid == valuetwo) if postexists == 0: if exists == 0: print("post wasnt previously on lb") if (len(reaction.message.attachments) > 0): post.insert({ 'msgid': valuetwo, 'username': username, 'points': 1, 'servers': server, 'content': reaction.message.content, 'embed': reaction.message.attachments[0].url }) else: post.insert({ 'msgid': valuetwo, 'username': username, 'points': 1, 'servers': server, 'content': reaction.message.content, 'embed': '' }) else: print("user has privacy mode on") else: print("post was previously on db") post.update(add('points', 1), where('msgid') == valuetwo) # Send a confirmation message result = db.get(Query()['username'] == value) heart = await channel.send( "**Hearted!** {} now has {} points. (+1)".format( reaction.message.author.name, result.get('points'))) await asyncio.sleep(3) await heart.delete() # ------------------------- # REACTION = :MINUS: # ------------------------- if reaction.emoji.name == 'minus': channel = reaction.message.channel # Add user to the points table value = str(reaction.message.author.id) exists = db.count(Query().username == value) server = str(reaction.message.guild.id) if exists == 0: print("user didnt exist.") db.insert({ 'username': value, 'points': -1, 'servers': [server] }) # Send a confirmation message result = db.get(Query()['username'] == value) crush = await channel.send( "**Crushed.** {} now has {} points. (-1)".format( reaction.message.author.name, result.get('points'))) await asyncio.sleep(3) await crush.delete() else: User = Query() serverid = str(reaction.message.guild.id) existsserver = db.count( (User.servers.any([serverid])) & (User.username == value)) # no funciona print(str(existsserver)) print("user does exist.") print("server id: " + serverid) print("is the server in the list?? = " + str(existsserver)) if existsserver == 0: print("server wasnt on the list.") db.update(subtract('points', 1), where('username') == value) l = str(db.search((User.username == value))) print(l) if "servers" not in l: print( "legacy user, didn't have any servers. added its first one" ) docs = db.search(User.username == value) for doc in docs: doc['servers'] = [str(server)] db.write_back(docs) else: print("added a new server!") db.update(add('servers', [server]), where('username') == value) else: print("server was on the list.") db.update(subtract('points', 1), where('username') == value) # Log post for post leaderboard priv.clear_cache() exists = priv.count( Query().username == reaction.message.author.id) valuetwo = str(reaction.message.id) username = str(reaction.message.author.id) postexists = post.count(Query().msgid == valuetwo) if postexists == 0: if exists == 0: print("post wasnt previously on lb") if (len(reaction.message.attachments) > 0): post.insert({ 'msgid': valuetwo, 'username': username, 'points': -1, 'servers': server, 'content': reaction.message.content, 'embed': reaction.message.attachments[0].url }) else: post.insert({ 'msgid': valuetwo, 'username': username, 'points': -1, 'servers': server, 'content': reaction.message.content, 'embed': '' }) else: print("user has privacy mode on") else: print("post was previously on db") post.update(subtract('points', 1), where('msgid') == valuetwo) # Send a confirmation message result = db.get(Query()['username'] == value) crush = await channel.send( "**Crushed.** {} now has {} points. (-1)".format( reaction.message.author.name, result.get('points'))) await asyncio.sleep(3) await crush.delete()
async def battleroyale(self, context, bet=None): """Starts a battle royale with a forced bet of _bet_ points.""" BaseCog.check_main_server(self, context) BaseCog.check_bot_channel(self, context) BaseCog.check_forbidden_characters(self, context) await BaseCog.dynamic_user_add(self, context) economy = BaseCog.load_dependency(self, 'Economy') main_db = economy.main_db stats = BaseCog.load_dependency(self, 'Stats') trivia_table = stats.trivia_table gambling = BaseCog.load_dependency(self, 'Gambling') weapon_emotes = gambling.weapon_emotes race_participants = None try: horserace = BaseCog.load_dependency(self, 'Horserace') race_participants = horserace.race_participants except DependencyLoadError: # If horse race cog is not available, shouldn't exit with error pass try: if not bet: await self.bot.post_error(context, '!battleroyale requires a forced bet.') return try: bet = int(bet) except ValueError: await self.bot.post_error(context, 'Bet must be an integer.') return if self.br_bet != 0: await self.bot.post_error(context, 'Not so hasty, courageous fighter. There is already a battle royale in progress.') return elif race_participants is not None and len(race_participants) > 0: await self.bot.post_error(context, 'Sorry ' + context.message.author.name + ', please wait for the ongoing horse race to end so that the messages don\'t interfere.') elif bet < self.br_min_bet: await self.bot.post_error(context, '!battleroyale requires the initial forced bet to be at least ' + str(self.br_min_bet) + ' ' + config.currency_name + 's.') return else: user_balance = main_db.get(self.bot.query.user == context.message.author.name)['balance'] # Check if battle royale is today's minigame for holiday points holidays = self.bot.get_cog('Holidays') is_holiday_minigame = False holiday = 0 if holidays is not None: if holidays.holiday_minigame.contains(self.bot.query.minigame == 'Battle Royale'): is_holiday_minigame = True holiday = main_db.get(self.bot.query.user == context.message.author.name)['holiday'] if user_balance + holiday < bet: await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** You do not have enough ' + config.currency_name + 's, ' + context.message.author.name + '. The desired entry fee is ' + str(bet) + ' ' + config.currency_name + 's and your current balance is ' + str(user_balance) + '.') return lock = True gambling = self.bot.get_cog('Gambling') if gambling is not None: lock = gambling.lock if lock: if bet > gambling.lock_max_bet: await self.bot.post_error(context, 'High-stakes gambling is not allowed. Please stay below ' + str(gambling.lock_max_bet) + ' ' + config.currency_name + 's, ' + context.message.author.name + '. Admins can remove this limit using !unlock.') return self.br_participants.append(context.message.author.name) self.br_pool = bet self.br_bet = bet if holiday > 0: leftover = bet - holiday if leftover > 0: # i.e. br bet > holiday points main_db.update(subtract('holiday', holiday), self.bot.query.user == context.message.author.name) self.br_holiday_points_used.append(holiday) main_db.update(subtract('balance', leftover), self.bot.query.user == context.message.author.name) main_db.update(subtract('gambling_profit', leftover), self.bot.query.user == context.message.author.name) else: # Note: holiday points do not count as negative gambling profit main_db.update(subtract('holiday', bet), self.bot.query.user == context.message.author.name) self.br_holiday_points_used.append(bet) else: main_db.update(subtract('balance', bet), self.bot.query.user == context.message.author.name) main_db.update(subtract('gambling_profit', bet), self.bot.query.user == context.message.author.name) self.br_holiday_points_used.append(0) announcement = self.br_last_ann while announcement == self.br_last_ann: announcement = random.choice(self.arena_init_texts).replace('[USER]', context.message.author.name) await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** ' + announcement) await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** Type !joinbr (entry fee is ' + str(bet) + ') to join the ranks of the challengers.') self.br_last_ann = announcement self.br_closed = False amount_asked = 0 while len(self.br_participants) < self.br_min_users and amount_asked < 3: if self.br_delay <= 60: await asyncio.sleep(self.br_delay) # during this time, people can use commands to join else: await asyncio.sleep(self.br_delay-60) # during this time, people can use commands to join await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** Battle royale will start in 1 minute. Type !joinbr to take part!') await asyncio.sleep(30) # during this time, people can use commands to join await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** Battle royale will start in 30 seconds. Type !joinbr to take part!') await asyncio.sleep(30) # during this time, people can use commands to join if len(self.br_participants) < self.br_min_users: await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** Waiting for more people to join the bloodshed (min ' + str(self.br_min_users) + ' participants).') amount_asked += 1 self.br_closed = True if len(self.br_participants) < self.br_min_users: await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** The battle royale has been canceled due to a lack of interest in the bloodshed. Cowards! (min ' + str(self.br_min_users) + ' participants).') for i, p in enumerate(self.br_participants): try: balance_p = main_db.get(self.bot.query.user == p)['balance'] gambling_pr = main_db.get(self.bot.query.user == p)['gambling_profit'] main_db.update({'gambling_profit': gambling_pr + (self.br_bet - self.br_holiday_points_used[i])}, self.bot.query.user == p) if self.br_holiday_points_used[i] > 0: holiday_p = main_db.get(self.bot.query.user == p)['holiday'] main_db.update({'holiday': holiday_p + self.br_holiday_points_used[i]}, self.bot.query.user == p) main_db.update({'balance': balance_p + self.br_bet - self.br_holiday_points_used[i]}, self.bot.query.user == p) else: main_db.update({'balance': balance_p + self.br_bet}, self.bot.query.user == p) except Exception as e: await self.bot.post_error(context, 'Could not refund bet to ' + context.message.author.name + '.', config.additional_error_message) log.exception(e) else: # _self.br_participants_ is now filled with usernames await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** Ladies and gentlemen, the battle royale is about to begin. ' + str(len(self.br_participants)) + ' brave fighters have stepped into the arena after ' + context.message.author.name + ' called for a grand battle. They fight over ' + str(self.br_pool) + ' ' + config.currency_name + 's. Additionally, at least 1 ' + config.currency_name + ' is granted for each kill on the field. Good luck! :drum:') dim_participants = self.br_participants[:] kill_map = defaultdict(int) time_intervals = [10, 12, 14, 16, 18, 20] weapons = {} last_killer = '' streak = 0 for p in self.br_participants: if p in self.custom_weapons: weapons[p] = self.custom_weapons[p] else: weapons[p] = random.choice(weapon_emotes) p_suicide = self.p_suicide p_block = self.p_block p_bomb_or_melee = self.p_bomb_or_melee p_exotic = self.p_exotic local_longest_streak = 0 local_longest_streak_user = None while len(dim_participants) > 1: await asyncio.sleep(random.choice(time_intervals)) if len(dim_participants) > 3: max_killed = math.ceil(len(dim_participants)/3) amnt_probabilities = [0.5] amnt_list = [] for i in range(1, max_killed): amnt_list.append(i) amnt_probabilities.append(0.5 / (max_killed - 1)) amnt_list.append(max_killed) x = random.uniform(0, 1) cum_prob = 0 for i, i_p in zip(amnt_list, amnt_probabilities): cum_prob += i_p if x < cum_prob: break amnt_killed = i else: amnt_killed = 1 for i in range(0, amnt_killed): killed = random.choice(dim_participants) event = random.uniform(0, 1) if event < p_suicide: if killed in self.custom_suicides: await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** ' + killed + ' ' + self.custom_suicides[killed]) else: suicide_emote = random.choice(self.suicide_emotes) await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** ' + killed + ' ' + suicide_emote + ' ' + killed) killed = dim_participants.pop(dim_participants.index(killed)) continue killer = killed while killed == killer: killer = random.choice(dim_participants) if event < (1-p_block + p_suicide): killed = dim_participants.pop(dim_participants.index(killed)) kill_map[killer] += 1 notes = [] if event < (p_suicide + p_bomb_or_melee): if event < ((p_suicide + p_bomb_or_melee) / 2): weapon = ':bomb:' notes.append('Bomb kill bonus: 1') else: weapon = ':right_facing_fist:' notes.append('Melee kill bonus: 1') kill_map[killer] += 1 elif event < p_suicide + p_bomb_or_melee + p_exotic: weapon = random.choice(self.exotic_weapons) notes.append('Exotic kill bonus: 10') kill_map[killer] += 10 else: weapon = weapons[killer] if last_killer == killer: streak += 1 kill_map[killer] += streak notes.append('Streak bonus: ' + str(streak)) if streak > local_longest_streak: local_longest_streak = streak local_longest_streak_user = killer else: if streak > 1 and killed == last_killer: notes.append('Shutdown bonus: 1') kill_map[killer] += 1 streak = 1 last_killer = killer result = '**[BATTLE ROYALE]** ' + killer + ' ' + weapon + ' ' + killed for note in notes: result += ' *(' + note + ')*' await self.bot.post_message(self.bot.bot_channel, result) else: await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** ' + killer + ' :shield: ' + killed) await self.bot.post_message(self.bot.bot_channel, '**[BATTLE ROYALE]** :confetti_ball: :confetti_ball: :confetti_ball: ' + dim_participants[0] + ' wins, taking home the pool of ' + str(self.br_pool) + ' ' + config.currency_name + 's! :confetti_ball: :confetti_ball: :confetti_ball:') result = '```Scoreboard ' + linesep + linesep indent = max(len(p) for p in self.br_participants) ctr = 1 kill_map[dim_participants[0]] += self.br_pool for p, k in sorted(kill_map.items(), key=itemgetter(1), reverse=True): result += p.ljust(indent) + ' ' + str(k) + linesep ctr += 1 for p in self.br_participants: if p not in kill_map: result += p.ljust(indent) + ' 0' + linesep ctr += 1 result += '```' await self.bot.post_message(self.bot.bot_channel, result) kill_map[dim_participants[0]] -= self.br_pool # Update winner balance try: balance_first = main_db.get(self.bot.query.user == dim_participants[0])['balance'] main_db.update({'balance': balance_first + self.br_pool}, self.bot.query.user == dim_participants[0]) except Exception as e: await self.bot.post_error(context, 'Could not update winner\'s balance.', config.additional_error_message) log.exception(e) # Update winner stats try: gambling_profit_first = main_db.get(self.bot.query.user == dim_participants[0])['gambling_profit'] main_db.update({'gambling_profit': gambling_profit_first + self.br_pool}, self.bot.query.user == dim_participants[0]) first_total_won = main_db.get(self.bot.query.user == dim_participants[0])['br_winnings'] main_db.update({'br_winnings': first_total_won + self.br_pool}, self.bot.query.user == dim_participants[0]) except Exception as e: await self.bot.post_error(context, 'Could not update winner\'s gambling stats.', config.additional_error_message) log.exception(e) # Kills try: highest_total_owned = trivia_table.get(self.bot.query.name == 'highest_total_owned')['value'] for p in self.br_participants: amnt_kills = kill_map[p] if amnt_kills > 0: try: balance = main_db.get(self.bot.query.user == p)['balance'] main_db.update({'balance': balance + amnt_kills}, self.bot.query.user == p) except Exception as e: await self.bot.post_error(context, 'Could not update balance for user ' + p + '.', config.additional_error_message) log.exception(e) gambling_profit = main_db.get(self.bot.query.user == p)['gambling_profit'] main_db.update({'gambling_profit': gambling_profit + amnt_kills}, self.bot.query.user == p) if amnt_kills > self.br_bet or p == dim_participants[0]: total_won = main_db.get(self.bot.query.user == p)['br_winnings'] main_db.update({'br_winnings': total_won + amnt_kills - self.br_bet}, self.bot.query.user == p) akills = main_db.get(self.bot.query.user == p)['br_score'] main_db.update({'br_score': akills + amnt_kills}, self.bot.query.user == p) new_balance = balance + amnt_kills if new_balance > highest_total_owned: trivia_table.update({'value': new_balance, 'person1': p, 'person2': 'None', 'date': datetime.datetime.now().strftime("%Y-%m-%d %H:%M")}, self.bot.query.name == 'highest_total_owned') highest_total_owned = new_balance except Exception as e: await self.bot.post_error(context, 'Could not update some stats/balances.', config.additional_error_message) log.exception(e) # Other try: maxkills = max(kill_map.items(), key=itemgetter(1)) trivia_table.update(increment('value'), self.bot.query.name == 'amnt_brs') main_db.update(increment('br_wins'), self.bot.query.user == dim_participants[0]) highest_br_pool = trivia_table.get(self.bot.query.name == 'highest_br_pool')['value'] largest_br = trivia_table.get(self.bot.query.name == 'largest_br')['value'] most_kills = trivia_table.get(self.bot.query.name == 'most_br_score')['value'] longest_streak = trivia_table.get(self.bot.query.name == 'longest_streak')['value'] if maxkills[1] > most_kills: trivia_table.update({'value': maxkills[1], 'person1': maxkills[0], 'person2': dim_participants[0], 'date': datetime.datetime.now().strftime("%Y-%m-%d %H:%M")}, self.bot.query.name == 'most_br_score') if self.br_pool > highest_br_pool: trivia_table.update({'value': self.br_pool, 'person1': dim_participants[0], 'person2': kill_map[dim_participants[0]], 'date': datetime.datetime.now().strftime("%Y-%m-%d %H:%M")}, self.bot.query.name == 'highest_br_pool') if local_longest_streak > longest_streak: trivia_table.update({'value': local_longest_streak, 'person1': local_longest_streak_user, 'person2': dim_participants[0], 'date': datetime.datetime.now().strftime("%Y-%m-%d %H:%M")}, self.bot.query.name == 'longest_streak') if len(self.br_participants) > largest_br: trivia_table.update({'value': len(self.br_participants), 'person1': dim_participants[0], 'person2': kill_map[dim_participants[0]], 'date': datetime.datetime.now().strftime("%Y-%m-%d %H:%M")}, self.bot.query.name == 'largest_br') except Exception as e: await self.bot.post_error(context, 'Could not update some battle royale stats (only affects !trivia output).', config.additional_error_message) log.exception(e) try: for p in self.br_participants: main_db.update(increment('brs'), self.bot.query.user == p) except Exception as e: await self.bot.post_error(context, 'Could not update some battle royale stats (only affects !trivia output).', config.additional_error_message) log.exception(e) except Exception as e: await self.bot.post_error(context, 'Oh no, something went wrong.', config.additional_error_message) log.exception(e) # Reset stuff self.br_closed = True self.br_pool = 0 self.br_bet = 0 self.br_participants = [] self.br_holiday_points_used = []
async def acceptduel(self, context): """Accept a duel.""" BaseCog.check_main_server(self, context) BaseCog.check_bot_channel(self, context) BaseCog.check_forbidden_characters(self, context) economy = BaseCog.load_dependency(self, 'Economy') main_db = economy.main_db stats = BaseCog.load_dependency(self, 'Stats') trivia_table = stats.trivia_table gambling = BaseCog.load_dependency(self, 'Gambling') weapon_emotes = gambling.weapon_emotes if not context.message.author.name in [ d[1] for d in self.duels.values() ]: await self.bot.post_error( context, 'You have not been challenged to a duel, ' + context.message.author.name + '.') elif context.message.author.name in [ d[0] for d in self.duels.values() ]: await self.bot.post_error( context, 'You have already challenged someone else to a duel, ' + context.message.author.name + ', you need to finish that duel before you can start another one.' ) else: challenger = None bet = None duel_id = None for did, (c, user, b, accepted) in self.duels.items(): if user == context.message.author.name and not accepted: challenger = c bet = b duel_id = did break if challenger is None: await self.bot.post_error( context, 'You have not been challenged to a duel, ' + context.message.author.name + '.') return user_balance = main_db.get( self.bot.query.user == context.message.author.name)['balance'] other_balance = main_db.get( self.bot.query.user == challenger)['balance'] if other_balance < bet: await self.bot.post_message( self.bot.bot_channel, '**[DUEL]** ' + challenger + ' doesn\'t even have ' + str(bet) + ' ' + config.currency_name + 's anymore, the duel has been canceled.') del self.duels[duel_id] elif user_balance < bet: await self.bot.post_message( self.bot.bot_channel, '**[DUEL]** You do not have enough ' + config.currency_name + 's, ' + context.message.author.name + '. ' + challenger + ' wants to fight over ' + str(bet) + ' ' + config.currency_name + 's and your current balance is ' + str(user_balance) + '.') del self.duels[duel_id] else: self.duels[duel_id] = (challenger, context.message.author.name, bet, True) try: main_db.update(subtract('balance', bet), self.bot.query.user == challenger) main_db.update( subtract('balance', bet), self.bot.query.user == context.message.author.name) main_db.update(subtract('gambling_profit', bet), self.bot.query.user == challenger) main_db.update( subtract('gambling_profit', bet), self.bot.query.user == context.message.author.name) except Exception as e: await self.bot.post_error( context, 'A fatal error occurred while trying to subtract ' + config.currency_name + 's from respective accounts. Duel is canceled and balances might be wrong.', config.additional_error_message) log.exception(e) else: try: await self.bot.post_message( self.bot.bot_channel, '**[DUEL]** Ladies and gentlemen, we are about to see a duel to the death between ' + challenger + ' and ' + context.message.author.name + '. Who is going to prevail, taking ' + str(bet) + ' ' + config.currency_name + 's from their opponent?') await asyncio.sleep( self.duel_battle_delay ) # nothing happens during this time duel_participants = [] duel_participants.append(context.message.author.name) duel_participants.append(challenger) # Choose winners first = random.choice(duel_participants) second = '' if first == context.message.author.name: second = challenger else: second = context.message.author.name balance_first = 0 try: balance_first = main_db.get( self.bot.query.user == first)['balance'] main_db.update( {'balance': balance_first + bet + bet}, self.bot.query.user == first) except Exception as e: await self.bot.post_error( context, 'A fatal error occurred while trying to add ' + config.currency_name + 's to ' + first + '\'s account. Balances might be wrong.', config.additional_error_message) log.exception(e) else: weapon = random.choice(weapon_emotes) await self.bot.post_message( self.bot.bot_channel, '**[DUEL]** ' + first + ' ' + weapon + ' ' + second) try: gambling_profit_first = main_db.get( self.bot.query.user == first)['gambling_profit'] main_db.update( { 'gambling_profit': gambling_profit_first + bet + bet }, self.bot.query.user == first) first_total_won_duels = main_db.get( self.bot.query.user == first)['duel_winnings'] main_db.update( { 'duel_winnings': first_total_won_duels + bet }, self.bot.query.user == first) highest_total_owned = trivia_table.get( self.bot.query.name == 'highest_total_owned')['value'] if balance_first + bet > highest_total_owned: trivia_table.update( { 'value': balance_first + bet, 'person1': first, 'person2': 'None', 'date': datetime.datetime.now().strftime( "%Y-%m-%d %H:%M") }, self.bot.query.name == 'highest_total_owned') except Exception as e: await self.bot.post_error( context, 'Could not update some stats (affects !trivia output).', config.additional_error_message) log.exception(e) try: main_db.update(increment('duel_wins'), self.bot.query.user == first) highest_duel = trivia_table.get( self.bot.query.name == 'highest_duel')['value'] if bet > highest_duel: trivia_table.update( { 'value': bet, 'person1': first, 'person2': second, 'date': datetime.datetime.now().strftime( "%Y-%m-%d %H:%M") }, self.bot.query.name == 'highest_duel') except Exception as e: await self.bot.post_error( context, 'Could not update some duel stats (affects !trivia output).', config.additional_error_message) log.exception(e) try: main_db.update(increment('duels'), self.bot.query.user == first) main_db.update(increment('duels'), self.bot.query.user == second) trivia_table.update( increment('value'), self.bot.query.name == 'amnt_duels') except Exception as e: await self.bot.post_error( context, 'Could not update some duel stats (affects !trivia output).', config.additional_error_message) log.exception(e) except Exception as e: await self.bot.post_error( context, 'Oh no, something went wrong (duel may or may not have finished).', config.additional_error_message) log.exception(e) del self.duels[duel_id]
async def give(self, context, user, amnt, reason=None): """Gives _amnt_ points to _user_. Must specify a _reason_.""" BaseCog.check_main_server(self, context) BaseCog.check_forbidden_characters(self, context) await BaseCog.dynamic_user_add(self, context) stats = BaseCog.load_dependency(self, 'Stats') trivia_table = stats.trivia_table try: quote = '' if context.message.channel != self.bot.bot_channel: quote = '`' + context.message.author.name + ': ' + context.message.content + '`' + linesep + linesep if not reason: await self.bot.post_error( context, 'You need to specify a reason to give points to ' + user + '.') elif not any(c.isalpha() for c in reason): await self.bot.post_error( context, 'Your specified reason does not contain any letters, so it cannot be reasonable (pun intended).' ) else: user = BaseCog.map_user(self, user) try: amnt = int(amnt) except ValueError: await self.bot.post_error( context, '!give requires a positive integer as second argument (amount of ' + config.currency_name + 's to give).') else: if amnt < 0: await self.bot.post_error( context, 'Cannot give a negative amount of ' + config.currency_name + 's.') elif self.main_db.contains(self.bot.query.user == user): if amnt > self.max_points_to_give_per_day: await self.bot.post_error( context, 'You cannot give ' + user + ' more than ' + str(self.max_points_to_give_per_day) + ' ' + config.currency_name + 's each day, ' + context.message.author.name + '.') return if self.give_table.contains( (self.bot.query.donor == context.message.author.name) & (self.bot.query.recipient == user)): already_given_amount_today = self.give_table.get( (self.bot.query.donor == context.message.author.name) & (self.bot.query.recipient == user))['amount'] if already_given_amount_today >= self.max_points_to_give_per_day: await self.bot.post_error( context, 'You have already given ' + user + ' ' + str(self.max_points_to_give_per_day) + ' ' + config.currency_name + 's today, ' + context.message.author.name + ', you will have to wait until tomorrow to give them any more points.' ) return elif already_given_amount_today + amnt > self.max_points_to_give_per_day: amnt = self.max_points_to_give_per_day - already_given_amount_today # < amnt await self.bot.post_error( context, 'You have already given ' + user + ' ' + str(already_given_amount_today) + ' ' + config.currency_name + 's today, ' + context.message.author.name + ', you can only give ' + str(amnt) + ' more.') quote = '' freep = 0 balance = 0 other_balance = 0 freep = self.main_db.get( self.bot.query.user == context.message.author.name)['free'] balance = self.main_db.get( self.bot.query.user == context.message.author.name)['balance'] other_balance = self.main_db.get( self.bot.query.user == user)['balance'] try: if user == context.message.author.name: await self.bot.post_error( context, 'You cannot give ' + config.currency_name + 's to yourself, ' + context.message.author.name + '.') return # not sure if necessary else: if freep < amnt: rest_pay = amnt - freep # always positive if rest_pay > balance: await self.bot.post_error( context, 'You do not have enough ' + config.currency_name + 's, ' + context.message.author.name + '. Your balance is ' + str(balance) + ' and you have ' + str(freep) + ' free points left to spend today. Use !loan <amount> to take out a loan in free points (automatically repaid the next day)' ) return else: self.main_db.update( {'balance': other_balance + amnt}, self.bot.query.user == user) self.main_db.update( { 'free': 0, 'balance': balance - rest_pay }, self.bot.query.user == context.message.author.name) await self.bot.post_message( self.bot.bot_channel, quote + '**[INFO]** ' + context.message.author.name + ' gave ' + str(freep) + ' free ' + config.currency_name + 's and ' + str(rest_pay) + ' ' + config.currency_name + 's to ' + user + '.') else: self.main_db.update( {'balance': other_balance + amnt}, self.bot.query.user == user) self.main_db.update( subtract('free', amnt), self.bot.query.user == context.message.author.name) await self.bot.post_message( self.bot.bot_channel, quote + '**[INFO]** ' + context.message.author.name + ' gave ' + str(amnt) + ' (free) ' + config.currency_name + 's to ' + user + '.') try: if self.give_table.contains( (self.bot.query.donor == context.message.author.name) & (self.bot.query.recipient == user)): already_given_amount_today = self.give_table.get( (self.bot.query.donor == context.message.author.name) & (self.bot.query.recipient == user ))['amount'] try: self.give_table.update( { 'amount': already_given_amount_today + amnt }, (self.bot.query.donor == context.message.author.name) & (self.bot.query.recipient == user)) except Exception as e: try: self.give_table.update( { 'amount': already_given_amount_today }, (self.bot.query.donor == context.message. author.name) & (self.bot.query.recipient == user)) except Exception as e2: await self.bot.post_error( context, 'A fatal error occured while trying to update ' + config.currency_name + 's given today from ' + context.message.author.name + ' to ' + user + '. Please note that the transaction may not have completed successfully and/or your balances might be wrong.' ) log.exception(e2) raise else: self.give_table.insert({ 'donor': context.message.author.name, 'recipient': user, 'amount': amnt }) except Exception as e: raise try: highest_total_owned = trivia_table.get( where('name') == 'highest_total_owned')['value'] if other_balance + amnt > highest_total_owned: trivia_table.update( { 'value': other_balance + amnt, 'person1': user, 'person2': 'None', 'date': datetime.datetime.now(). strftime("%Y-%m-%d %H:%M") }, self.bot.query.name == 'highest_total_owned') given_total = self.main_db.get( self.bot.query.user == context.message.author.name)['given'] self.main_db.update( {'given': given_total + amnt}, self.bot.query.user == context.message.author.name) received_total = self.main_db.get( self.bot.query.user == user)['received'] self.main_db.update( {'received': received_total + amnt}, self.bot.query.user == user) except Exception as e: await self.bot.post_error( context, 'Could not update some stats (only affects !trivia output).' ) log.exception(e) except Exception as e: try: self.main_db.update( {'balance': other_balance}, self.bot.query.user == user) self.main_db.update( {'free': freep}, self.bot.query.user == context.message.author.name) self.main_db.update( {'balance': balance}, self.bot.query.user == context.message.author.name) await self.bot.post_error( context, 'Oh no, something went wrong.') except Exception as e2: await self.bot.post_error( context, 'A fatal error occured while trying to reset balances. Please note that the transaction may not have completed successfully and/or your balances might be wrong.' ) log.exception(e2) else: await self.bot.post_error( context, '' + user + ' has not been added yet. They need to type !add to initialize their account.' ) except Exception as e: raise e finally: # If this is not the bot channel, delete the message but still quote it in the bot channel. if context.message.channel != self.bot.bot_channel: await context.message.delete()