def fetch_stream(self, number=100): documents = [] horizon = datetime.datetime.now() - datetime.timedelta(weeks=1) for name in self.subscriptions_comment: subscribee = get_user(name) documents.extend(Comment.all().filter( 'author ==', subscribee).filter('date >=', horizon).order('-date').fetch(number)) for name in self.subscriptions_document: subscribee = get_user(name) documents.extend(Document.all().filter( 'author ==', subscribee).filter('date >=', horizon).order('-date').fetch(number)) for tag in self.subscriptions_tag: documents.extend(get_documents([tag], number=number)) documents.extend(self.streamMessages) ordered = sorted(documents, key=lambda document: document.date, reverse=True) return ordered[:number]
def view_topic(topic_id, task=None): print_topic = [] edit, delete = None, None if functions.islogin() == False: red = make_response(redirect('/')) return red user = functions.get_user() if task == '': if user[0]["privileges"] == 0: red = make_response(redirect('/')) return red if user[0]["privileges"] == 1: if task == 'edit' and request.method == 'POST': title = request.form['title'] text = request.form['text'] functions.query_db2( "UPDATE topics SET title = ?, text = ? WHERE id = ?", [title, text, topic_id]) red = make_response(redirect('/view/' + str(topic_id) + '/')) return red if task == 'delete': functions.query_db2("DELETE FROM topics WHERE id = ?", [topic_id]) red = make_response(redirect('/')) return red elif task == 'edit': edit = True elif task == 'delete': delete = True args = { 'path': request.url_root, 'url': request.url, 'app_settings': app_settings(), 'categories': arrays.categories(), 'profile': functions.get_user(), 'topic': print_topic, 'edit': edit, 'delete': delete, 'topic_id': topic_id } topic = {} for row in functions.query_db('SELECT * FROM topics WHERE id = ? Limit 1', [topic_id]): topic["title"] = Markup(row["title"]) topic["text"] = Markup(row["text"]) topic["id"] = row["id"] topic["upload"] = row["linked_upload"] print_topic.append(topic) if topic == {}: red = make_response(redirect('/')) return red return render_template('view.html', **args)
def remove(self): affected = [] for username in self.circle: other = get_user(username) other.circlepermissions.remove(self.username) other.put() affected.append(other) for username in self.circlepermissions: other = get_user(username) other.circle.remove(self.username) other.put() affected.append(other) for username in self.invitations: other = get_user(username) other.invitees.remove(self.username) other.put() affected.append(other) for username in self.invitees: other = get_user(username) other.invitations.remove(self.username) other.put() affected.append(other) for username in self.subscribers: other = get_user(username) other.set_subscription([], self.username) affected.append(other) for username in self.subscriptions_user: self.set_subscription([], username) affected.append(other) for comment in self.mycomments: #potential ERROR if some comments are descendants of others comment.remove() for document in self.works: document.remove() for message in self.streamMessages: message.remove() for rating in self.ratings: rating.delete() self.delete()
def remove(self): affected = [] for username in self.circle: other = get_user(username) other.circlepermissions.remove(self.username) other.put() affected.append(other) for username in self.circlepermissions: other = get_user(username) other.circle.remove(self.username) other.put() affected.append(other) for username in self.invitations: other = get_user(username) other.invitees.remove(self.username) other.put() affected.append(other) for username in self.invitees: other = get_user(username) other.invitations.remove(self.username) other.put() affected.append(other) for username in self.subscribers: other = get_user(username) other.set_subscription([],self.username) affected.append(other) for username in self.subscriptions_user: self.set_subscription([],username) affected.append(other) for comment in self.mycomments: #potential ERROR if some comments are descendants of others comment.remove() for document in self.works: document.remove() for message in self.streamMessages: message.remove() for rating in self.ratings: rating.delete() self.delete()
def home(self, env, params={}): if (self.session_id is None): return self.redirect_to(env, to='/', params=params) print('home') # print(self.cookie) try: user = get_user(name=None, id=self.user_id) error = self.sessions[self.session_id].get('error', None) if (error is None): error_tag = '' else: font_color = self.sessions[self.session_id].get( 'font_color', None) self.sessions[self.session_id] = {} error_tag = "<font color='{font_color}'>{error}</font>".format( font_color=font_color, error=error) with open('../template/home.html', 'r', encoding='utf-8') as fp: html = fp.read() html = html.replace('{error_tag}', error_tag) html = html.replace('{name}', user['name']) html = html.replace('{id}', str(user['id'])) html = html.replace('{points}', str(user['points'])) html = html.replace('{fee}', str(GAME_CONFIG['fee'])) body = [html.encode('utf-8')] except Exception as e: # print(str(e)) # logging.error(str(e)) raise (e) return self.internal_server_error(env, params) status = '200 OK' headers = [('Content-Type', 'text/html; charset=utf-8')] headers = set_cookie(headers, self.cookie) return status, headers, body
def set_subscription(self, subscriptions, subscribee): """ SUBSCRIPTIONS is a list of values one each for email and stream subscription on either comments or documents. Subscribee should be a username string. """ flag = None subscribee = get_user(subscribee) if not subscriptions: if self.username in subscribee.subscribers: subscribee.subscribers.remove(self.username) if subscribee.username in self.subscriptions_user: self.subscriptions_user.remove(subscribee.username) message = 'This user has been removed from your subscriptions.' else: if self.username not in subscribee.subscribers: subscribee.subscribers.append(self.username) flag = 1 if subscribee.username not in self.subscriptions_user: self.subscriptions_user.append(subscribee.username) flag = 1 if flag: message = 'This user has been added to your subscriptions.' else: message = 'Your settings have been saved.' if 'subscribe_publish' in subscriptions: if not subscribee.username in self.subscriptions_document: self.subscriptions_document.append(subscribee.username) else: if subscribee.username in self.subscriptions_document: self.subscriptions_document.remove(subscribee.username) if 'email_publish' in subscriptions: if not self.username in subscribee.subscribers_document: subscribee.subscribers_document.append(self.username) else: if self.username in subscribee.subscribers_document: subscribee.subscribers_document.remove(self.username) if 'subscribe_comment' in subscriptions: if not subscribee.username in self.subscriptions_comment: self.subscriptions_comment.append(subscribee.username) else: if subscribee.username in self.subscriptions_comment: self.subscriptions_comment.remove(subscribee.username) if 'email_comment' in subscriptions: if not self.username in subscribee.subscribers_comment: subscribee.subscribers_comment.append(self.username) else: if self.username in subscribee.subscribers_comment: subscribee.subscribers_comment.remove(self.username) subscribee.put() self.put() return message
async def forex(message, arguments): if arguments: base_currency = str(arguments[0]).upper() amount = float(arguments[1]) currency = str(arguments[2]).upper() base_currency = get_user_currency( user_id=get_user(discord_id=message.author.id).first().id, short_code=base_currency).first() currency = get_currency(short_code=currency).first() required_fee = ( convert_currency(currency.short_code, base_currency.short_code) * amount) if base_currency and base_currency.amount >= required_fee: if currency: add_currency_to_user( get_user(discord_id=message.author.id).first().id, currency.short_code, amount) remove_currency_from_user( get_user(discord_id=message.author.id).first().id, base_currency.short_code, required_fee) await message.channel.send( _("{user} paid {amount} {currency} and bought {converted_amount} {converted_currency}." ).format_map({ "user": message.author.name, "amount": required_fee, "currency": base_currency.short_code, "converted_amount": amount, "converted_currency": currency.short_code })) else: await message.author.send(_("Invalid currency.")) else: await message.author.send( _("You don't have enough {currency} to exchange.").format_map( {"currency": base_currency.short_code})) else: await send_usage_message( message.channel, _("{prefix}forex (Currency (SELL)) (Purchase amount) (Currency (BUY))" ).format_map({"prefix": Config.COMMAND_PREFIX}))
def declineInvitation(self, username): self.invitations.remove(username) inviter = get_user(username) inviter.invitees.remove(self.username) self.put() inviter.put() # steam message message = StreamMessage() message.recipient = inviter message.content = self.get_url(html=True)+' has declined your circle invitation.' message.put()
def withdrawCircle(self, username): self.invitees.remove(username) other = get_user(username) other.invitations.remove(self.username) self.put() other.put() # stream message message = StreamMessage() message.recipient = other message.content = self.get_url(html=True)+'\'s Writer\'s Circle invitation has been withdrawn.' message.put()
def set_view(self): if not self.draft: self.views += 1 user = get_user() try: user.username if not user.username in self.viewers: self.viewers.append(user.username) except: pass self.put()
def fetch_stream(self,number=100): documents=[] horizon = datetime.datetime.now()-datetime.timedelta(weeks=1) for name in self.subscriptions_comment: subscribee = get_user(name) documents.extend(Comment.all().filter('author ==',subscribee).filter('date >=', horizon).order('-date').fetch(number)) for name in self.subscriptions_document: subscribee = get_user(name) documents.extend(Document.all().filter('author ==',subscribee).filter('date >=', horizon).order('-date').fetch(number)) for tag in self.subscriptions_tag: documents.extend(get_documents([tag],number=number)) documents.extend(self.streamMessages) ordered = sorted(documents, key=lambda document: document.date, reverse=True) return ordered[:number]
def leaveCircle(self, username): self.circlepermissions.remove(username) other = get_user(username) other.circle.remove(self.username) self.put() other.put() # stream message message = StreamMessage() message.recipient = other message.content = self.get_url(html=True)+' has left your Writer\'s Circle' message.put()
def invite(self, username): if not username in self.invitees: self.invitees.append(username) invited = get_user(username) invited.invitations.append(self.username) self.put() invited.put() # stream message message = StreamMessage() message.recipient = invited message.content = 'You\'ve been invited to join '+self.get_url(html=True)+'\'s Writer\'s Circle' message.put()
def set_rating(self): votes = self.ratings rating = 0; view_mass = 0; for viewer in self.viewers: user_view = get_user(viewer) view_mass = view_mass + (1+user_view.reputation) for vote in votes: rating = rating + vote.value*(1+vote.user.reputation) rating = rating/view_mass self.rating = rating self.put()
def withdrawCircle(self, username): self.invitees.remove(username) other = get_user(username) other.invitations.remove(self.username) self.put() other.put() # stream message message = StreamMessage() message.recipient = other message.content = self.get_url( html=True) + '\'s Writer\'s Circle invitation has been withdrawn.' message.put()
def removeCircle(self, username): """Ejects username from this user's circle""" self.circle.remove(username) other = get_user(username) other.circlepermissions.remove(self.username) self.put() other.put() # stream message message = StreamMessage() message.recipient = other message.content = 'You have been removed from '+self.get_url(html=True)+'\'s Writer\'s Circle' message.put()
def leaveCircle(self, username): self.circlepermissions.remove(username) other = get_user(username) other.circle.remove(self.username) self.put() other.put() # stream message message = StreamMessage() message.recipient = other message.content = self.get_url( html=True) + ' has left your Writer\'s Circle' message.put()
def set_rating(self): votes = self.ratings rating = 0 view_mass = 0 for viewer in self.viewers: user_view = get_user(viewer) view_mass = view_mass + (1 + user_view.reputation) for vote in votes: rating = rating + vote.value * (1 + vote.user.reputation) rating = rating / view_mass self.rating = rating self.put()
def declineInvitation(self, username): self.invitations.remove(username) inviter = get_user(username) inviter.invitees.remove(self.username) self.put() inviter.put() # steam message message = StreamMessage() message.recipient = inviter message.content = self.get_url( html=True) + ' has declined your circle invitation.' message.put()
def removeCircle(self, username): """Ejects username from this user's circle""" self.circle.remove(username) other = get_user(username) other.circlepermissions.remove(self.username) self.put() other.put() # stream message message = StreamMessage() message.recipient = other message.content = 'You have been removed from ' + self.get_url( html=True) + '\'s Writer\'s Circle' message.put()
def invite(self, username): if not username in self.invitees: self.invitees.append(username) invited = get_user(username) invited.invitations.append(self.username) self.put() invited.put() # stream message message = StreamMessage() message.recipient = invited message.content = 'You\'ve been invited to join ' + self.get_url( html=True) + '\'s Writer\'s Circle' message.put()
def acceptInvitation(self, username): self.circlepermissions.append(username) self.invitations.remove(username) inviter = get_user(username) inviter.invitees.remove(self.username) inviter.circle.append(self.username) self.put() inviter.put() # stream message message = StreamMessage() message.recipient = inviter message.content = self.get_url(html=True)+' has accepted your circle invitation.' message.put()
def signup(self, env, params={}): home_url = util.application_uri(env) try: name = params.get('name', 'guest') pwd = params.get('password', 'guest') params = {} # print("name: {}, pure_pwd: {}".format(name, pwd)) res = get_user(name=name) print('signup_user: '******'error': 'user already exiets', 'font_color': 'red' } redirect_url = home_url else: if (set_user(name, pwd)): print("ユーザーの作成に成功") error_dict = { 'error': 'signup success', 'font_color': 'green' } redirect_url = home_url else: print("ユーザーの作成に失敗") error_dict = { 'error': 'signup failed', 'font_color': 'red' } redirect_url = home_url except Exception as e: # print(str(e)) # logging.error(str(e)) raise (e) return self.internal_server_error(env, params) self.sessions[self.session_id] = error_dict status = '303 See Other' headers = [('Content-type', 'text/html'), ('Location', redirect_url)] headers = set_cookie(headers, self.cookie) body = ["<p>リダイレクト中</p>".encode('utf-8')] return status, headers, body
def __init__(self, username, document_filename=None,document_title=None): if document_filename: document = get_document(username, document_filename) draftCheck = document.draft self.comments = document.comments.order('-date').filter('draft ==',draftCheck) else: self.comments = get_user(username).mypagecomments.order('-date') self.comment_tree = self.prepare_reply_tree(self.comments) self.delta = self.delta_builder(self.comment_tree[1]) self.sum_delta = [1] * sum([item for sublist in self.delta for item in sublist]) self.keys = [str(comment.key()) for comment in self.comment_tree[0]] self.comment_data = zip(self.comment_tree[0], self.keys, self.delta)
def acceptInvitation(self, username): self.circlepermissions.append(username) self.invitations.remove(username) inviter = get_user(username) inviter.invitees.remove(self.username) inviter.circle.append(self.username) self.put() inviter.put() # stream message message = StreamMessage() message.recipient = inviter message.content = self.get_url( html=True) + ' has accepted your circle invitation.' message.put()
async def bahissonucu(message, arguments): if message.author.permissions_in(message.channel).administrator: bet_id = int(arguments[0]) bet_result = int(arguments[1]) bet = get_bet(id=bet_id).first() if bet_result: await message.channel.send( _("Result of \"{bet}\": `WON`").format_map({"bet": bet.bet})) else: await message.channel.send( _("Result of \"{bet}\": `LOST`").format_map({"bet": bet.bet})) for bet_player in get_user_bet(bet_id=bet_id).all(): discord_user = await client.get_user_info( get_user(id=bet_player.user_id).first().discord_id) if bet_result: award = float(bet.rate * bet_player.deposit) add_currency_to_user(bet_player.user_id, Config.CURRENCY_CODE, award) await message.channel.send( _("{user} has successfully predicted this bet and won {award} {currency}." ).format_map({ "user": discord_user.name, "award": award, "currency": Config.CURRENCY_CODE })) else: await message.channel.send( _("{user} lost {deposit} {currency}.").format_map({ "user": discord_user.name, "deposit": bet_player.deposit, "currency": Config.CURRENCY_CODE })) session.delete(bet_player) session.commit() session.delete(bet) session.commit() else: await message.channel.send(_("You don't have access to this command."))
def __init__(self, username, document_filename=None, document_title=None): if document_filename: document = get_document(username, document_filename) draftCheck = document.draft self.comments = document.comments.order('-date').filter( 'draft ==', draftCheck) else: self.comments = get_user(username).mypagecomments.order('-date') self.comment_tree = self.prepare_reply_tree(self.comments) self.delta = self.delta_builder(self.comment_tree[1]) self.sum_delta = [1] * sum( [item for sublist in self.delta for item in sublist]) self.keys = [str(comment.key()) for comment in self.comment_tree[0]] self.comment_data = zip(self.comment_tree[0], self.keys, self.delta)
def parseFunctions(self, user, channel, msg): """Executes all of the function commands""" if msg.startswith("!user"): msg = functions.get_user(msg) elif msg.startswith("!weather"): msg = functions.weather(msg) elif msg.startswith("!jerkcity"): msg = functions.jerkcity() elif msg.startswith("!seen"): msg = self.seen.get_seen(msg) else: msg = "Invalid Request" self.msg(channel, msg)
def login(self, env, params={}): try: name = params.get('name', 'guest') pwd = params.get('password', 'guest') params = {} res = get_user(name=name) print('login_user: '******'id'] print("認証成功") # set_user_session(self.session_id, res['id']) error_dict = { 'error': 'login success', 'font_color': 'green' } to = '/home' else: print("認証失敗") error_dict = { 'error': 'authentification error', 'font_color': 'red' } to = '/' else: print("ユーザーが存在しない。新規登録画面へ遷移") error_dict = {'error': 'user not found', 'font_color': 'red'} to = '/' except Exception as e: # print(str(e)) # logging.error(str(e)) # raise(e) return self.internal_server_error(env, params) self.sessions[self.session_id] = error_dict return self.redirect_to(env, to=to, params=params)
def categorys(cat_id): if functions.islogin() == False: red = make_response(redirect('/')) return red topics = [] args = { 'path': request.url_root, 'url': request.url, 'app_settings': app_settings(), 'categories': arrays.categories(), 'topics': topics, 'profile': functions.get_user() } for row in functions.query_db('SELECT id, title FROM topics WHERE cat = ?', [cat_id]): topic = {} topic["title"] = row["title"] topic["id"] = row["id"] topics.append(topic) return render_template('categories.html', **args)
async def bahisbelirle(message, arguments): if message.author.permissions_in(message.channel).administrator: bet_rate = float(arguments[0]) bet_bet = message.content[message.content. find(" ", message.content.find(" ") + 1):] bet = create_bet( get_user(discord_id=message.author.id).first().id, bet_bet, bet_rate) await message.channel.send( _("{user} has opened a new bet: `{bet} ({bet_rate})`").format_map({ "user": message.author, "bet": bet_bet, "bet_rate": bet_rate })) else: await message.channel.send(_("You don't have access to this command."))
async def para(message, arguments): user_currencies = get_user_currency(user_id=get_user( discord_id=message.author.id).first().id).all() counter = 0 embed = discord.Embed( title=_("*{user} has the following currencies:*").format_map( {"user": message.author.name}), color=0x008000) embed.set_author(name=_("Bank of {server}").format_map( {"server": message.channel.server.name})) for currency in user_currencies: embed.add_field(name=currency.short_code, value=str(currency.amount), inline=True) counter += 1 if not counter: embed.description = _("This person doesn't have any currencies.") await message.channel.send(embed=embed)
async def on_message(message): # Parsing and forwarding the command, if message starts with bot prefix. if message.content.startswith(Config.COMMAND_PREFIX): command = message.content.split()[0][1:] arguments = [] try: arguments = message.content.split()[1:] except IndexError: pass try: await getattr(commands, command)(message, arguments) except Exception as e: logger.error(e) print(e) # Checking user, and adding to database if not exists. user = get_user(discord_id=message.author.id).first() if not user: user = create_user(discord_id=message.author.id) # Properly rewarding user for contribution. if not message.content.startswith(Config.COMMAND_PREFIX): message_length = len(message.content) add_currency_to_user(user.id, Config.CURRENCY_CODE, int(message_length / 5)) # Checking currency conversion data request time. last_update = get_system_variable("currency_last_update") if not last_update: last_update = create_system_variable("currency_last_update", get_current_date()) if (get_current_date() - datetime.strptime(last_update.value, "%Y-%m-%d %H:%M:%S.%f")) >= timedelta(hours=1): update_currencies() last_update.value = get_current_date() session.commit()
def app_settings(): user = functions.get_user() is_login = functions.islogin() title = 'Теми за държавен изпит' unicode = 'utf8' menu = [ { "url": "/", "name": "Начало" }, ] if is_login and user[0]["privileges"] == 1: menu += [{"url": "/admin", "name": "Админ панел"}] if is_login: menu += [{"url": "/logout/", "name": "Излизане"}] adminmenu = [ { "url": "/admin/categories/", "name": "Категории" }, { "url": "/admin/topics/", "name": "Добави урок" }, { "url": "/admin/users/", "name": "Потребители" }, { "url": "/", "name": "Към сайта" }, ] return title, unicode, menu, adminmenu
def index(): find_username = request.cookies.get('username') find_password = request.cookies.get('password') if find_username and find_password: args = { 'path': request.url_root, 'url': request.url, 'app_settings': app_settings(), 'categories': arrays.categories(), 'username': find_username, 'profile': functions.get_user(), } return render_template('index.html', **args) else: if request.method == 'POST': username = request.form['username'] password = request.form['password'] hashed_password = hashlib.md5(password.encode('utf8')).hexdigest() if username != "" and password != "": if functions.isuser(username, hashed_password): expire_date = datetime.datetime.now() expire_date = expire_date + datetime.timedelta(days=90) response = make_response(redirect('/')) response.set_cookie('username', username, expires=expire_date) response.set_cookie('password', hashed_password, expires=expire_date) return response else: error = 'Потребителскто име или парола не са намерени.' return render_template('login.html', error=error) else: error = 'Моля попълнете всички полета.' return render_template('login.html', error=error) return render_template('login.html')
def show_user(self, event): """在用户下拉菜单中显示已选用户组中的所有用户列表""" self.select_user_combobox['value'] = fc.get_user(self.select_group_combobox.get())
def game(self, env, params={}): if (self.session_id is None): return self.redirect_to(env, to='/', params=params) print('game') # print(self.cookie) # print(self.user_id) user = get_user(name=None, id=self.user_id) try: game_list = self.sessions[self.session_id].get('game', None) game = None if game_list is None else copy.deepcopy(game_list[-1]) print(game) if (game is None): if (user['points'] < GAME_CONFIG['fee']): with open('../template/game-result.html', 'r') as fp: html = fp.read() html = html.replace( '{message}', '持ち点がゲーム参加に必要な{}ポイントに足りていません。'.format( GAME_CONFIG['fee'])) body = [html.encode('utf-8')] status = '200 OK' headers = [('Content-Type', 'text/html; charset=utf-8')] headers = set_cookie(headers, self.cookie) return status, headers, body print('game init') update_user_points(user['id'], user['points'] - GAME_CONFIG['fee']) self.sessions[self.session_id]['game'] = [] game = { 'turn': 0, 'MAX': random.randint(15, 30), 'TURN_MAX': random.randint(3, 6), 'count': 0, 'turn_count': 0, 'my_count': 0, 'is_finished': 0 } status = '200 OK' headers = [('Content-Type', 'text/html; charset=utf-8')] headers = set_cookie(headers, self.cookie) elif (game['is_finished'] != 0): print('finish') my_count = game['my_count'] if (game['is_finished'] == 1): point = my_count * GAME_CONFIG['mag'] message = 'YOU WIN!!\n{}ポイント獲得!!'.format(point) update_user_points(self.user_id, user['points'] + point) user_status = '現在の所有ポイントは{}ポイントです。'.format( str(user['points'] + point)) elif (game['is_finished'] == -1): message = 'YOU LOSE...' user_status = '現在の所有ポイントは{}ポイントです。'.format( str(user['points'])) with open('../template/game-result.html', 'r') as fp: html = fp.read() html = html.replace('{message}', message) html = html.replace('{user_status}', user_status) body = [html.encode('utf-8')] status = '200 OK' headers = [('Content-Type', 'text/html; charset=utf-8')] headers = set_cookie(headers, self.cookie) self.sessions[self.session_id]['game'] = None return status, headers, body else: MAX = game['MAX'] TURN_MAX = game['TURN_MAX'] if ('plus' in params.keys()): print('plus') if (game['turn_count'] >= TURN_MAX): return self.redirect_to(env, to='/home/game', params=params) game['turn_count'] += 1 game['count'] += 1 game['my_count'] += 1 if (game['count'] >= MAX): game['is_finished'] = -1 self.sessions[self.session_id]['game'] += [ dict(game.items()) ] gamelog = game_log(self.sessions[self.session_id].get( 'game', None)) return self.redirect_to(env, to='/home/game', params=params) else: pass elif ('submit' in params.keys()): print('npc') game["turn"] = 1 game['turn_count'] = 0 if (game['count'] == MAX - 1): game['count'] += 1 game['is_finished'] = 1 self.sessions[self.session_id]['game'] += [ dict(game.items()) ] gamelog = game_log(self.sessions[self.session_id].get( 'game', None)) return self.redirect_to(env, to='/home/game', params=params) if (MAX - 1 - game['count'] <= TURN_MAX): while game["count"] < MAX - 1: game['count'] += 1 self.sessions[self.session_id]['game'] += [ dict(game.items()) ] else: add = random.randint(1, TURN_MAX) for _ in range(add - 1): game['count'] += 1 self.sessions[self.session_id]['game'] += [ dict(game.items()) ] game['count'] += 1 self.sessions[self.session_id]['game'] += [ dict(game.items()) ] game['turn'] = -1 self.sessions[self.session_id]['game'] += [ dict(game.items()) ] game["turn"] = 0 else: print('else') print('end: ', end='') self.sessions[self.session_id]['game'] += [dict(game.items())] gamelog = game_log(self.sessions[self.session_id].get( 'game', None)) message = '{}に到達したら負け。<br>1ターンで{}回カウンターを増やせます。'.format( game['MAX'], game['TURN_MAX']) if (game['turn_count'] == 0): input_tag = \ """ <div class="form_contents"> <form method="POST" action='/home/game'> <input class="send_btn" type="submit" id="plus" name="plus" value="+"/> </form> </div> """ elif (game['turn_count'] >= TURN_MAX): input_tag = \ """ <div class="form_contents"> <form method="POST" action='/home/game'> <input class="send_btn" type="submit" id="submit" name="submit" value='ターン終了'/> </form> </div> """ game['turn_count'] = 0 game['turn'] = -1 else: input_tag = \ """ <div class="form_contents" style="width: 50%;"> <form method="POST" action='/home/game'> <input class="send_btn" type="submit" id="submit" name="submit" value='ターン終了'/> </form> </div> <div class="form_contents" style="width: 50%;"> <form method="POST" action='/home/game'> <input class="send_btn" type="submit" id="plus" name="plus" value="+"/> </form> </div> """ # print(message) with open('../template/game.html', 'r', encoding='utf-8') as fp: html = fp.read() html = html.replace('{message}', message) # html = html.replace('{count}', str(game['count'])) html = html.replace('{MAX}', str(game['MAX'])) html = html.replace('{TURN_MAX}', str(game['TURN_MAX'])) html = html.replace('{input_tag}', input_tag) html = html.replace('{log}', str(gamelog)) body = [html.encode('utf-8')] status = '200 OK' headers = [('Content-Type', 'text/html; charset=utf-8')] headers = set_cookie(headers, self.cookie) return status, headers, body except Exception as e: # print(str(e)) # logging.error(str(e)) raise (e) return self.internal_server_error(env, params) status = '200 OK' headers = [('Content-Type', 'text/html; charset=utf-8')] headers = set_cookie(headers, self.cookie) return status, headers, body
# user ID card scanned f.update_user(int(upc[-5:-1])) if upc[6] == '2': # nullary command functions cmd_id = int(upc[-5:-1]) if cmd_id == 1: from subprocess import call call(['git', 'pull']) elif upc[0] in [str(i) for i in [0,1,6,7,8]]: user = f.get_user() username = (('.@' + user.twitter_handle if user.twitter_handle else user.name) if user else 'Somebody') beveragename = f.get_beverage_description(upc) print 'beveragename: ', beveragename if not beveragename: beveragename = 'something' f.twitter_post('%s grabbed a %s' % (username, beveragename)) else: print 'don\'t know what that is'
async def bahisoyna(message, arguments): if arguments: if int(arguments[0]) < 1: await message.channel.send(_("Invalid bet number.")) elif int(arguments[1]) < 1: await message.channel.send(_("Invalid bet amount.")) else: bet_id = int(arguments[0]) bet_amount = float(arguments[1]) bet = get_bet(id=arguments[0]).first() if bet is None: await message.channel.send(_("Invalid bet number.")) else: current_user = get_user(discord_id=message.author.id).first() user_currency = get_user_currency( currency_id=Config.CURRENCY_CODE, user_id=current_user.id).first() if user_currency is None or user_currency.amount < bet_amount: await message.channel.send( _("You don't have have enough {currency}.").format_map( {"currency": Config.CURRENCY_NAME})) else: remove_currency_from_user( get_user(discord_id=message.author.id).first().id, Config.CURRENCY_CODE, bet_amount) user_bet = get_user_bet(user_id=current_user.id, bet_id=bet.id).first() if user_bet: user_bet.deposit += bet_amount session.commit() await message.channel.send( _("You have added {bet_amount} {bet_currency} to your previous bet on #{bet_id}, making a total of {total_bet_amount} {bet_currency} on that bet." ).format_map({ "bet_id": bet.id, "bet_amount": bet_amount, "bet_currency": Config.CURRENCY_CODE, "total_bet_amount": user_bet.deposit })) else: user_bet = create_user_bet(current_user.id, bet.id, bet_amount) await message.channel.send( _("You betted {bet_amount} {bet_currency} for #{bet_id}." ).format_map({ "bet_id": bet.id, "bet_amount": bet_amount, "bet_currency": Config.CURRENCY_CODE })) else: await send_usage_message( message.channel, _("{prefix}bahisoyna (Bet Number) (Bet Amount)*").format_map( {"prefix": Config.COMMAND_PREFIX}))
async def rulet(message, arguments): bet_types = [{ "id": 0, "name": _("red"), "multiplier": 2 }, { "id": 1, "name": _("black"), "multiplier": 2 }, { "id": 2, "name": _("green"), "multiplier": 36 }, { "id": 3, "name": _("odd"), "multiplier": 2 }, { "id": 4, "name": _("even"), "multiplier": 2 }, { "id": 5, "name": _("number (0-36)"), "multiplier": 36 }, { "id": 6, "name": _("first column"), "multiplier": 3 }, { "id": 7, "name": _("second column"), "multiplier": 3 }, { "id": 8, "name": _("third column"), "multiplier": 3 }, { "id": 9, "name": _("first dozen"), "multiplier": 3 }, { "id": 10, "name": _("second dozen"), "multiplier": 3 }, { "id": 11, "name": _("third dozen"), "multiplier": 3 }] if arguments: bet_amount = 0 bet_type = None if len(arguments) > 2: arguments[1] = "%s %s" % (arguments[1], arguments[2]) try: bet_amount = float(arguments[0]) except Exception as e: await message.author.send(_("Invalid bet amount.")) try: for type in bet_types: if type["name"].lower() == arguments[1].lower(): bet_type = type if not bet_type: for i in range(36): if str(i) == arguments[1]: bet_type = bet_types[5] if not bet_type: await message.author.send(_("Invalid bet type.")) except Exception as e: await message.author.send(_("Invalid bet type.")) user_currency = get_user_currency( user_id=get_user(discord_id=message.author.id).first().id, short_code=Config.CURRENCY_CODE).first() if bet_type: if user_currency.amount >= bet_amount: remove_currency_from_user( get_user(discord_id=message.author.id).first().id, Config.CURRENCY_CODE, bet_amount) random_generator = randint(0, 36) won = False red_values = [ 1, 3, 5, 7, 9, 12, 14, 16, 18, 21, 23, 25, 27, 28, 30, 32, 34, 36 ] black_values = [ 2, 4, 6, 8, 10, 11, 13, 15, 17, 19, 20, 22, 24, 26, 29, 31, 33, 35 ] first_column = [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34] second_column = [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35] third_column = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36] if bet_type["id"] == 0: for value in red_values: if random_generator == value: won = True elif bet_type["id"] == 1: for value in black_values: if random_generator == value: won = True elif bet_type["id"] == 2: if random_generator == 0: won = True elif bet_type["id"] == 3: if (random_generator % 2) == 1: won = True elif bet_type["id"] == 4: if (random_generator % 2) == 0: won = True elif bet_type["id"] == 5: if random_generator == int(arguments[1]): won = True elif bet_type["id"] == 6: for value in first_column: if random_generator == value: won = True elif bet_type["id"] == 7: for value in second_column: if random_generator == value: won = True elif bet_type["id"] == 8: for value in third_column: if random_generator == value: won = True elif bet_type["id"] == 9: for value in range(1, 12): if random_generator == value: won = True elif bet_type["id"] == 10: for value in range(13, 24): if random_generator == value: won = True elif bet_type["id"] == 11: for value in range(25, 36): if random_generator == value: won = True color = None for value in red_values: if random_generator == value: color = 0xff0000 for value in black_values: if random_generator == value: color = 0x000000 if random_generator == 0: color == 0x00ff00 embed = discord.Embed(title=_("**Roulette**"), description=str(random_generator), color=color) embed.set_author(name=Config.BOT_NAME) await message.channel.send(embed=embed) if won: won_amount = bet_type["multiplier"] * bet_amount add_currency_to_user( get_user(discord_id=message.author.id).first().id, Config.CURRENCY_CODE, won_amount) await message.channel.send( _("You won! {amount} {currency} added to your bank account." ).format_map({ "amount": won_amount, "currency": Config.CURRENCY_CODE })) else: await message.channel.send(_("Sorry, you lost.")) else: await message.author.send( _("You don't have have enough {currency}.").format_map( {"currency": Config.CURRENCY_NAME})) else: bet_type_list = "" count = 0 for type in bet_types: if count == 0: bet_type_list += type["name"] else: bet_type_list += ", %s" % (type["name"]) count += 1 await send_usage_message( message.channel, _("{prefix}roulette (Bet ({currency})) (Bet Type ({bet_type_list}))" ).format_map({ "prefix": Config.COMMAND_PREFIX, "currency": Config.CURRENCY_CODE, "bet_type_list": bet_type_list }))
async def blackjack(message, arguments): game_over = False def deal(deck): hand = [] for i in range(2): shuffle(deck) card = deck.pop() if card == 11: card = "J" if card == 12: card = "Q" if card == 13: card = "K" if card == 14: card = "A" hand.append(card) return hand def total(hand): total = 0 for card in hand: if card == "J" or card == "Q" or card == "K": total += 10 elif card == "A": if total >= 11: total += 1 else: total += 11 else: total += card return total def hit(hand): card = deck.pop() if card == 11: card = "J" if card == 12: card = "Q" if card == 13: card = "K" if card == 14: card = "A" hand.append(card) return hand def win(): add_currency_to_user( get_user(discord_id=message.author.id).first().id, Config.CURRENCY_CODE, (bet * 2)) async def print_results(dealer_hand, player_hand, dealer_turn=False): if dealer_turn: await message.channel.send( _("Dealer has {dealer_hand} in total of {total}.").format_map({ "dealer_hand": str(dealer_hand), "total": str(total(dealer_hand)) })) else: await message.channel.send( _("Dealer shows a {dealer_hand}.").format_map( {"dealer_hand": str(dealer_hand[0])})) await message.channel.send( _("You have {player_hand} in total of {total_player_hand}."). format_map({ "player_hand": str(player_hand), "total_player_hand": str(total(player_hand)) })) async def bjack(dealer_hand, player_hand): if total(player_hand) == 21: await print_results(dealer_hand, player_hand) await message.channel.send(_("BLACKJACK!") + "\n") win() elif total(dealer_hand) == 21: await print_results(dealer_hand, player_hand) await message.channel.send( _("Sorry, you lost. Dealer hit a blackjack.") + "\n") def winner_control(dealer_hand, player_hand): if total(player_hand) == 21: return True elif total(dealer_hand) == 21: return False elif total(player_hand) > 21: return False elif total(dealer_hand) > 21: return True elif total(player_hand) < total(dealer_hand): return False elif total(player_hand) > total(dealer_hand): return True def blackjack_control(dealer_hand, player_hand): if total(player_hand) == 21: return True elif total(dealer_hand) == 21: return True async def score(dealer_hand, player_hand, dealer_turn=False): if total(player_hand) == 21: await print_results(dealer_hand, player_hand, dealer_turn) await message.channel.send(_("BLACKJACK!") + "\n") win() elif total(dealer_hand) == 21: await print_results(dealer_hand, player_hand, dealer_turn) await message.channel.send( _("Sorry, you lost. Dealer hit a blackjack.") + "\n") elif total(player_hand) > 21: await print_results(dealer_hand, player_hand, dealer_turn) await message.channel.send(_("You busted. You lost.") + "\n") elif total(dealer_hand) > 21: await print_results(dealer_hand, player_hand, dealer_turn) await message.channel.send(_("Dealer busted. You won!") + "\n") elif total(player_hand) < total(dealer_hand): await print_results(dealer_hand, player_hand, dealer_turn) if dealer_turn: await message.channel.send( _("Dealer has a higher hand. You lost.") + "\n") elif total(player_hand) > total(dealer_hand): await print_results(dealer_hand, player_hand, dealer_turn) if dealer_turn: await message.channel.send( _("You have a higher hand. You won!") + "\n") win() def check_message(message): if message.content.lower().find( _("hit")) != -1 or message.content.lower().find( _("stop")) != -1: return True else: return False if arguments: bet = 0 try: bet = float(arguments[0]) except Exception: bet = 0 user_currency = get_user_currency( user_id=get_user(discord_id=message.author.id).first().id, short_code=Config.CURRENCY_CODE).first() if user_currency.amount >= bet: remove_currency_from_user( get_user(discord_id=message.author.id).first().id, Config.CURRENCY_CODE, bet) deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] * 4 choice = "" dealer_hand = deal(deck) player_hand = deal(deck) message_text = _("You put {amount} {currency}.").format_map({ "amount": bet, "currency": Config.CURRENCY_CODE }) dealer_message = await message.channel.send(message_text) message_text += "\n" + _("Dealing cards...") await client.edit_message(dealer_message, message_text) message_text += "\n" + _( "Dealer shows a {dealer_hand}.").format_map( {"dealer_hand": str(dealer_hand[0])}) await client.edit_message(dealer_message, message_text) message_text += "\n" + _( "You have {player_hand} in total of {total_player_hand}." ).format_map({ "player_hand": str(player_hand), "total_player_hand": str(total(player_hand)) }) await client.edit_message(dealer_message, message_text) while choice.find(_("stop")) == -1 and total( player_hand) < 21 and not blackjack_control( dealer_hand, player_hand): await message.channel.send( _("Would you like to [hit], or [stop]?")) message = await client.wait_for_message(author=message.author, check=check_message) choice = message.content.lower() if choice.find(_("hit")) != -1: hit(player_hand) await score(dealer_hand, player_hand, False) if not winner_control(dealer_hand, player_hand): choice = _("stop") elif choice.find(_("stop")) != -1: while total(dealer_hand) < total(player_hand): hit(dealer_hand) await bjack(dealer_hand, player_hand) await score(dealer_hand, player_hand, True) if blackjack_control(dealer_hand, player_hand): await score(dealer_hand, player_hand, False) else: await message.channel.send( _("You don't have have enough {currency}.").format_map( {"currency": Config.CURRENCY_NAME}) + "\n") else: await send_usage_message( message.channel, _("{prefix}blackjack (Bet ({amount}))").format_map({ "prefix": Config.COMMAND_PREFIX, "amount": Config.CURRENCY_CODE }))
def win(): add_currency_to_user( get_user(discord_id=message.author.id).first().id, Config.CURRENCY_CODE, (bet * 2))