def get(self): # Get the id that indicate where is the start point of new messages: current_id = int(self.request.get('id')) messages = Message.all().order('-postID').filter("postID > ", current_id) msg_set = messages.fetch(10) self.response.headers['Content-Type'] = 'text/xml' self.response.headers['Cache-Control'] = 'no-cache' # Start writing the xml content: self.response.out.write('<?xml version="1.0"?>\n') self.response.out.write(' <response>\n') self.response.out.write(' <id>%d</id>\n' % Message.max_id() ) for msg in msg_set: if not msg.isRemoved: self.response.out.write(' <message>\n') self.response.out.write(' <author>%s</author>\n' % msg.author.nickname() ) self.response.out.write(' <postID>%d</postID>\n' % msg.postID ) self.response.out.write(' <content>%s</content>\n' % msg.content ) self.response.out.write(' <rcount>%d</rcount>\n' % msg.rCount ) self.response.out.write(' <time>%s</time>\n' % msg.postDate ) self.response.out.write(' </message>\n') self.response.out.write(' </response>\n')
def put(): key = ndb.Key('Message', pk) msg = key.get() if msg: msg = Message(key=key, **form.data) msg.put() return msg
def restore_object(self, attrs, instance=None): user = self.context['request'].user classgroup = attrs.get('classgroup') attributes = ["text", "source", "reply_to"] if (classgroup.class_settings is not None and classgroup.class_settings.enable_posting is False and not ClassGroupPermissions.is_teacher(classgroup, user)): raise serializers.ValidationError("You are not allowed to make a post right now.") if instance is None: instance = Message(user=user, classgroup=classgroup) else: if instance.user != user: raise serializers.ValidationError("Attempting to edit a message that is not yours.") message_type = attrs.get('message_type') if message_type == "A" and not ClassGroupPermissions.is_teacher(classgroup, user): raise serializers.ValidationError("You cannot make an announcement unless you own a course.") instance.message_type = message_type instance = set_attributes(attributes, attrs, instance) instance.save() return instance
def _enqueue_job_message(job, message_type): params = { 'message_type': message_type, 'params': json.dumps(job.to_json()) } Message.enqueue(params)
def _enqueue_lead_message(lead): params = { 'message_type': 'OFFER_TO_PROPERTY_OWNER', 'params': json.dumps(lead) } Message.enqueue(params)
def get(self): chat_key = self.request.get('key') form = self.request.get('format') if form == 'json': self.response.out.headers['Content-Type'] = 'application/zip' in_memory = StringIO() zmemory = zipfile.ZipFile(in_memory, "w", zipfile.ZIP_DEFLATED) zmemory.writestr( 'messages.json', '[ {} ]'.format(','.join( [json.dumps(m) for m in Message.query_all_from_chat(chat_key,limit=False)]))) in_memory.seek(0) zmemory.close() self.response.out.write(in_memory.read()) else: self.response.out.headers['Content-Type'] = 'text/plain' for message in Message.query_all_from_chat(chat_key,limit=True): self.response.out.write( u'{}, {}: {}\n'.format(message['author'], message['date'], message['text']) )
def post(self): request_dict = request.get_json() if not request_dict: response = {'message': 'No input data provided'} return response, status.HTTP_400_BAD_REQUEST errors = message_schema.validate(request_dict) if errors: return errors, status.HTTP_400_BAD_REQUEST message_message = request_dict['message'] if not Message.is_unique(id=0, message=message_message): response = {'error': 'A message with the same message already exists'} return response, status.HTTP_400_BAD_REQUEST try: category_name = request_dict['category']['name'] category = Category.query.filter_by(name=category_name).first() if category is None: # Create a new Category category = Category(name=category_name) db.session.add(category) # Now that we are sure we have a category # create a new Message message = Message( message=message_message, duration=request_dict['duration'], category=category) message.add(message) query = Message.query.get(message.id) result = message_schema.dump(query).data return result, status.HTTP_201_CREATED except SQLAlchemyError as e: db.session.rollback() resp = {"error": str(e)} return resp, status.HTTP_400_BAD_REQUEST
def send(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): msg = Message() msg.username = form.cleaned_data['username'] msg.email = form.cleaned_data['email'] msg.phone = form.cleaned_data['phone'] msg.location = form.cleaned_data['location'] msg.job = form.cleaned_data['job'] msg.description = form.cleaned_data['description'] msg.area = form.cleaned_data['area'] try: msg.save() mail_managers('ZUBIRD webpage - new message received', 'Otrzymałeś nową wiadomość.') except Exception as e: import traceback logger.error(str(e)) logger.error(traceback.format_exc()) return render_to_response('error.html', {}) return render_to_response('thanks.html', {}) else: return render_to_response('base.html', Context({'form':form})) else: return index(request)
def save_msg(): form = request.form author = form.get("author") content = form.get("content") msg = Message(author=author, content=content, time=datetime.now()) msg.save() return jsonify(status='success')
def post(self, *args, **kwargs): groupname = kwargs['groupname'] query = Group.query(Group.name == groupname) groups = query.fetch() if len(groups) == 1: thisGroup = groups[0] else: thisGroup = None user = self.user print(user) if user: memberships = GroupMembership.query(GroupMembership.userKey == user.key, GroupMembership.groupKey == thisGroup.key).fetch() if len(memberships) == 1: membership = memberships[0] print(membership) else: self.display_message('You can only post if you\'re a member') return if user: print(self.request.get('message')) newMessage = Message(parent=thisGroup.key, userKey=user.key, text=self.request.get('message')) newMessage.put() self.redirect('/{groupname}/show'.format(groupname = groupname))
def obj_get_list(self, bundle, **kwargs): user = bundle.request.GET.get('user_id') #extracts user_id from URL params if bundle.request.GET.get('received'): received = False if bundle.request.GET.get('received') == "false" else True return Message.objects(user_id=user, received=received) else: return Message.objects(user_id=user)
def displaycontrol(request): """ If the request is a GET, renders the display control dialog content. If it's a POST, uses the POST data to send a Message to Harvest. That Message requests a change to a given client's display's hardware state, depending on the command specified in the request. The client's user must be an administrator for the Message to be sent. """ if request.method == 'GET': return render_to_response('orwell/displaycontrol.html', {}, context_instance=RequestContext(request)) else: if not request.user.is_staff: return HttpResponse('DISALLOWED') clientid = request.POST.get('client', '') client = get_object_or_404(Client, client_id=clientid) setpower = request.POST.get('setpower', '') cmd = request.POST.get('cmd', '') arg = request.POST.get('arg', '') packet = {'to':client.jid(), 'method':'displaycontrol'} if setpower == 'kill': packet['method'] = 'killDDS' if setpower in ['on', 'off']: packet['setpower'] = setpower == 'on' elif cmd != '' and arg != '': packet['cmd'] = {'cmd':cmd, 'arg':arg} if (('setpower' in packet) or ('cmd' in packet) or (packet['method'] == 'killDDS')): m = Message(message=json.dumps(packet)) m.save() return HttpResponse('OK')
def add_message_without_storage(to_user, from_user, level, message, extra_tags='', fail_silently=False, subject='', mail=False, expires=None, close_timeout=None): """ Use this method to add message without having to pass a `request.storage` """ from models import Message message = Message(user=to_user, level=level, message=message, extra_tags=extra_tags, subject=subject, from_user=from_user, expires=expires, close_timeout=close_timeout) return message.save()
def handle_received_message(self, sender, room_id, username, message, date, **kwargs): """ Default handler for the message_received signal. 1 - Saves an instance of message to db 2 - Appends a tuple (message_id, message_obj) to the sender.messages queue 3 - Signals the "New message" event on the sender (decorator) 4 - Returns the created message """ room = Room.objects.get(id=room_id) fields = { 'room': room, 'date': date, 'content': message, 'username': username, } user = kwargs.get('user') if user: fields['user'] = user # 1 new_message = Message(**fields) new_message.save() # 2 msg_number = sender.get_next_message_id(room_id) messages_queue = sender.get_messages_queue(room_id) messages_queue.append((msg_number, new_message)) # 3 - decorator does # sender.signal_new_message_event(room_id) # 4 return new_message
def send_msg(request): response = {} info = "" try: if request.method == 'POST': req = request.POST recv_user = req.get('recv_user') send_user = req.get('send_user') title = req.get('title') content = req.get('content') msg = Message(title=title, content=content) # 发送者ID为1则是系统信息 if send_user == 1: msg.category = 1 msg.save() user_msg = UserMessage(recv_user=recv_user,send_user=send_user,message=msg) user_msg.save() response['status'] = user_msg.status except: info = "%s || %s" % (sys.exc_info()[0], sys.exc_info()[1]) return HttpResponse(info) response_json = simplejson.dumps(response) return HttpResponse(response_json)
def do_ntranslate(singular, plural, number, translation_function): language = trans_real.get_language() translation = trans_real.translation(language) number = translation.plural(number) kw = {'msgid': singular, 'plural': number, 'language': language, 'domain': 'django'} try: message = Message.objects.get(**kw) except Message.DoesNotExist: # Miss msgstr = do_ntranslate_old(singular, plural, number, translation_function) kw['msgstr'] = msgstr message = Message(**kw) message.save() return msgstr # Hit translation = message.translation if not translation: return do_ntranslate_old(singular, plural, number, translation_function) return translation
def message_send(service): text = request.form.get('message') if not text: return Error.ARGUMENT_MISSING('message') subscribers = Subscription.query.filter_by(service=service).count() if subscribers == 0: # Pretend we did something even though we didn't # Nobody is listening so it doesn't really matter return Error.NONE level = (request.form.get('level') or '3')[0] level = int(level) if level in "12345" else 3 title = request.form.get('title', '').strip()[:255] link = request.form.get('link', '').strip() msg = Message(service, text, title, level, link) db.session.add(msg) db.session.commit() if google_api_key or current_app.config['TESTING']: Gcm.send_message(msg) if zeromq_relay_uri: queue_zmq_message(json_encode({"message": msg.as_dict()})) service.cleanup() db.session.commit() return Error.NONE
def create_message(email_message): if email_message: message = Message() message.subject = email_message.subject message.sent_date = email_message.sent_date message.message_id = email_message.message_id message.thread_id = email_message.thread_id # where should this logic live?
def post(self): "We receive post data from IMified" userkey = self.request.get('userkey') network = self.request.get('network') # remove any markup from messages msg = HTML_ELEMENTS.sub('', self.request.get('msg')) step = self.request.get('step') try: # we try and create the message message = Message( userkey = userkey, network = network, msg = msg, step = int(step) ) message.put() # send an email with the message on mail.send_mail(sender="*****@*****.**", to="Gareth Rushgrove <*****@*****.**>", subject="New message posted on IMified demo", body=msg) # we just added a message so we need to clear our cache memcache.delete("index") # simple logging logging.info("Saved new message") # the response is send as an IM message to the sender self.response.out.write('Message saved') except: # we'll log the error if it occurs # and report we couldn't save the message to the sender logging.error("Error occured creating new message") self.response.out.write('An error ocured, message not saved')
def setUp(self): self.n1, self.n2 = uuid.uuid4().hex, uuid.uuid4().hex self.k1, self.k2 = fakePublicKey(), fakePublicKey() self.u1 = User.create(self.n1, self.k1) self.u2 = User.create(self.n2, self.k2) self.m1 = Message.create(self.u1, self.u2, 'u1->u2') self.m2 = Message.create(self.u2, self.u1, 'u2->u1') self.m3 = Message.create(self.u1, self.u2, 'u1=>u2')
def contact(): form = ContactForm() if form.validate_on_submit(): message = Message(content = form.content.data) message.put() flash('Thanks, your message has been submitted') return redirect(url_for('contact')) return render_template('contact.html', form=form)
def save(self): message = Message( leave_by=self.user, subject=self.cleaned_data['subject'], content=self.cleaned_data['content'] ) message.save() return message
def run_index_page(): """ Return index page on bottle freamework """ some_post = Message() new_dict = some_post.get_message_by_key() return bottle.template("index.html", {"message_list": new_dict})
def home_screen(request): context = {} if 'submit' in request.POST: msge = Message(name=request.POST['name'], email=request.POST['email'], message=request.POST['message']) msge.save() context.update({'message': 'Successfully Saved', 'messagetype': 'success'}) context.update(csrf(request)) return render(request, 'index.html', context)
def postmessage(request): name = request.POST['name'] text = request.POST['text'] m = Message(name=name, text=text) m.save() return HttpResponseRedirect(reverse('board'))
def message_create(request): if request.method == "POST": form = MessageForm(request.POST) if form.is_valid(): # TODO: content_object msg = Message(msg=form.cleaned_data["msg"], user=request.user) msg.save() return HttpResponseRedirect("/")
def addMessage(request): user = request.POST.get("user", "nobody") message = request.POST.get("message", "") time = datetime.datetime.now() msg = Message(user=user, body=message, time=time) msg.save() msg_to_send = json.dumps({"user":user,"message":message, "time":time.strftime("%H:%S-%d/%m/%Y")}) conn.send(msg_to_send, destination='/messages') return HttpResponse("ok")
def create_tables(): from models import User, Message, Note, Relationship, City, Pinche # User.create_table() Relationship.create_table() Note.create_table() Message.create_table() City.create_table() Pinche.create_table()
def post(self): input_message = self.request.get("input_message") message = Message(text_entered=input_message) message.put() #return self.write("You've entered: " + input_message) return self.redirect_to("main")
def message_with_content_create(request): if request.method == "POST": form = MessageWithContentForm(request.POST) if form.is_valid(): msg = Message(msg=form.cleaned_data["msg"], user=request.user, content_type=form.cleaned_data["content_type"], object_id=form.cleaned_data["object_id"]) msg.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
def run_as_callback(action_cls, update: Update, context: CallbackContext): """Assign this class method as telegram dispatcher callback.""" message = Message.create_from_update(update) action_cls(message=message, bot=context.bot).do()
def get(self, message_id): message = Message.get_by_id(int(message_id)) params = {"message": message} return self.render_template("message_delete.html", params=params)
def get(self): messages = Message.select().where(Message.deleted == False) params = {"messages": messages} return self.render_template("guestbook.html", params=params)
def get(self, message_id): existing_message = Message.get_by_id(int(message_id)) params = {"message": existing_message} return self.render_template("entries_edit.html", params=params)
def get(self): all_entries = Message.query().fetch() params = {"everything": all_entries} return self.render_template("entries.html", params=params)
def messages_show(message_id): """Show a message.""" message = Message.get_message_by_id(message_id) return render_template('messages/show.html', message=message)
def handle_inv(payload, sock): inv_vec = InventoryVector.parse(payload) getdata = GetData(items=inv_vec.items) msg = Message(getdata.command, getdata.serialize()) sock.send(msg.serialize()) print("sent getdata")
def send_getblocks(sock): locator = construct_block_locator_for_blocks() getblocks = GetBlocks(locator) msg = Message(getblocks.command, getblocks.serialize()) sock.send(msg.serialize()) print('sent getblocks')
def send_getheaders(sock): locator = construct_block_locator() getheaders = GetHeaders(locator) msg = Message(getheaders.command, getheaders.serialize()) sock.send(msg.serialize()) print('sent getheaders')
def get(self): sporocila = Message.query().fetch() izpis = {"sporocila": sporocila} return self.render_template("shrani.html", izpis)
def get(self): message = Message.query().fetch() params = {} params["messages"] = message return self.render_template("liste.html", params)
def post(self): params = {} params["publish"] = self.request.get("some_text") message = Message(message_text=params["publish"]) message.put() return self.render_template("result.html", params)
def show_likes_page(user_id): """Show user likes page""" liked = [x.id for x in g.user.likes if x.user_id != g.user.id] messages = Message.get_liked_messages(liked) likes = [x.id for x in g.user.likes if x.id != g.user.id] return render_template('users/likes.html', user=g.user, messages=messages, likes=likes)
def add_msg(self, status, msg): m = Message(self.user_id(), status, msg) if m.reader_id: m.save()
def test_users_likes(self): """Test the /users/user_id/likes page""" edward = User(email="*****@*****.**", username="******", password="******", location="Oakland") juan = User(email="*****@*****.**", username="******", password="******", location="New York") timmy = User(email="*****@*****.**", username="******", password="******", location="Antarctica") db.session.add_all([edward, juan, timmy]) db.session.commit() user_ids = {'edward': edward.id, 'juan': juan.id, 'timmy': timmy.id} # POSTED BY EDWARD edwards_message = Message(text="test message 1", user_id=user_ids['edward']) # POSTED BY TIMMY timmys_message = Message(text="test message 2", user_id=user_ids['timmy']) db.session.add_all([edwards_message, timmys_message]) db.session.commit() # LETS LIKE SOME THINGS # EDWARD LIKES TIMMYS POST edward.messages_liked.append(Message.query.get(timmys_message.id)) # JUAN LIKES EDWARDS POST juan.messages_liked.append(Message.query.get(edwards_message.id)) db.session.commit() with self.client as c: # Let's make sure our session knows we are test user "edward" with c.session_transaction() as sess: sess[CURR_USER_KEY] = user_ids['edward'] # View edwards followers resp = c.get(f'/users/{user_ids["edward"]}/likes') self.assertEqual(resp.status_code, 200) #test list group items of liked posts on page self.assertNotIn(b'@juan', resp.data) self.assertIn(b'@timmy', resp.data) # check that only solid stars self.assertIn(b'class="fas fa-star', resp.data) self.assertNotIn(b'class="far fa-star', resp.data)
def add_message(text, user_id): m = Message(text=text, user_id=user_id) return m
def get(self, message_id): entry_message = Message.get_by_id(int(message_id)) params = {"message": entry_message} return self.render_template("entry_details.html", params=params)
def post(self, message_id): message = Message.get_by_id(int(message_id)) message.deleted = True message.put() return self.redirect_to("msg-list")
def post(self, message_id): new_text = self.request.get("some_text") message = Message.get_by_id(int(message_id)) message.text = new_text message.put() return self.redirect_to("singleentry")
def get(self): messages = Message.query().fetch() params = {"messages": messages} return self.render_template("guestbook.html", params=params)
def update_messages(username, mes, datetime): message_to_commit = Message(user=username, mes=mes, date=datetime) db.session.add(message_to_commit) db.session.commit()
cursor = cnx.cursor() parser = argparse.ArgumentParser() parser.add_argument("-u", "--username", help="username") parser.add_argument("-p", "--password", help="password (min 8 characters)") parser.add_argument("-t", "--to", help="message recipient") parser.add_argument("-s", "--send", help="message text (max 255 characters)") parser.add_argument("-l", "--list", help="list all messages", action="store_true") args = parser.parse_args() if args.list and args.username and args.password and not args.send and not args.to: user_list_by_username = User.load_user_by_username(cursor=cursor, username=args.username) if user_list_by_username: if check_password(pass_to_check=args.password, hashed=user_list_by_username.hashed_password): messages = Message.load_all_messages(cursor=cursor) for message in messages: user_data_by_id = User.load_user_by_id(cursor=cursor, id_=message.from_id) if message.to_id == user_list_by_username.id: print('From', user_data_by_id.username, ':', message.text, '- Sent on', message.creation_date) else: print('Incorrect password') else: print('User not found') elif args.username and args.password and args.send and args.to and not args.list: user_find_by_username = User.load_user_by_username(cursor=cursor, username=args.username) if user_find_by_username: if check_password(pass_to_check=args.password, hashed=user_find_by_username.hashed_password): recipient_find_by_username = User.load_user_by_username(cursor=cursor, username=args.to) if recipient_find_by_username: if len(args.send) <= 255:
def initdb_command(): """Reinitializes the database""" db.drop_all() db.create_all() db.session.commit() users = [] users.append(User('Bob', 'Smith', '*****@*****.**', '1111111111', '123')) #1 users.append(User('Carol', 'Stevens', '*****@*****.**', '1111111111', '123')) #2 users.append(User('Anna', 'Martin', '*****@*****.**', '1111111111', '123')) #3 users.append(User('Daniel', 'Rutgers', '*****@*****.**', '1111111111', '123')) #4 users.append(User('Frank', 'Lorris', '*****@*****.**', '1111111111', '123')) #5 users.append(User('John', 'McNault', '*****@*****.**', '1111111111', '123')) #6 users.append(User('Peter', 'Johnson', '*****@*****.**', '1111111111', '123')) #7 users.append(User('Laura', 'Smith', '*****@*****.**', '1111111111', '123')) #8 users.append(User('Jennifer', 'Raj', '*****@*****.**', '1111111111', '123')) #9 users.append(User('Quan', 'Billson', '*****@*****.**', '1111111111', '123')) #10 users.append(User('Jamil', 'Reckta', '*****@*****.**', '1111111111', '123')) #11 users.append(User('Victor', 'Rapedip', '*****@*****.**', '1111111111', '123')) #12 users.append(User('Mark', 'Zuck', '*****@*****.**', '1111111111', '123')) #13 users.append(User('Laura', 'shpeng', '*****@*****.**', '1111111111', '123')) #14 for x in users: db.session.add(x) db.session.commit() groups = [] groups.append( Group('CS1530 Guys', 'A bunch of dudes studying software engineering', 1)) #group 1 groups.append(Group('CS1530 Girls', 'Ladies is pimps too', 1)) #group 2 groups.append(Group('Go Eagles', 'Phily > PIttsburgh', users[3].id)) #group 3 for x in groups: db.session.add(x) db.session.commit() users[0].groups.append(groups[0]) users[3].groups.append(groups[0]) users[4].groups.append(groups[0]) users[1].groups.append(groups[1]) users[2].groups.append(groups[1]) users[5].groups.append(groups[0]) users[6].groups.append(groups[1]) users[7].groups.append(groups[1]) users[8].groups.append(groups[0]) users[9].groups.append(groups[2]) users[10].groups.append(groups[2]) users[11].groups.append(groups[2]) users[12].groups.append(groups[2]) users[13].groups.append(groups[1]) db.session.commit() courses = [] courses.append( Course('Software Engineering', 'Formal methods of software engineering', 'CS', 1530)) #0 courses.append( Course('Database Management Systems', 'Database Management Systems', 'CS', 1555)) #1 courses.append(Course('Web Applications', 'Web Applications', 'CS', 1520)) #2 courses.append(Course('Operating Systems', 'Operating Systems', 'CS', 1550)) #3 courses.append( Course('Interface Design Methodology', 'Interface design for mobile applications', 'CS', 1635)) #4 courses.append( Course('High performance computing', 'Introduction to high performance computing', 'CS', 1645)) #5 courses.append( Course('Intro to Data Science', 'Intro to Data Science', 'CS', 1656)) #6 courses.append( Course('Intmdt Prog Using Java', 'Intermediate programming with java', 'CS', 401)) #7 courses.append( Course('Data Structures', 'Intro to data structures', 'CS', 445)) #8 courses.append( Course('Intro to System Software', 'Introduction to system software', 'CS', 449)) #9 for x in courses: db.session.add(x) db.session.commit() for i, x in enumerate(users): if i < 5: x.current_courses.append(courses[0]) x.current_courses.append(courses[1]) x.current_courses.append(courses[2]) x.current_courses.append(courses[3]) x.current_courses.append(courses[4]) else: x.current_courses.append(courses[5]) x.current_courses.append(courses[6]) x.current_courses.append(courses[7]) x.current_courses.append(courses[8]) x.current_courses.append(courses[9]) users.append(User('John', 'Doe', '*****@*****.**', '1111111111', '123')) for i, x in enumerate(users): if i < 7: x.past_courses.append(courses[5]) x.past_courses.append(courses[6]) x.past_courses.append(courses[7]) x.past_courses.append(courses[8]) x.past_courses.append(courses[9]) else: x.past_courses.append(courses[0]) x.past_courses.append(courses[1]) x.past_courses.append(courses[2]) x.past_courses.append(courses[3]) x.past_courses.append(courses[4]) db.session.commit() groups[0].group_courses.append(courses[0]) groups[1].group_courses.append(courses[0]) groups[2].group_courses.append(courses[3]) db.session.commit() convos = [] # group_id, tutor_id, student_id convos.append(Conversation(None, users[2].id, users[3].id)) #1 convos.append(Conversation(groups[0].id, None, users[3].id)) #2 convos.append(Conversation(groups[1].id, None, users[1].id)) #3 convos.append(Conversation(None, users[1].id, users[0].id)) #4 convos.append(Conversation(groups[2].id, None, users[4].id)) #5 convos.append(Conversation(None, users[6].id, users[7].id)) #6 convos.append(Conversation(None, users[9].id, users[8].id)) #7 convos.append(Conversation(None, users[10].id, users[12].id)) #8 for x in convos: db.session.add(x) db.session.commit() messages = [] messages.append( Message(users[2].id, datetime.datetime.now(), "What time would be good to meet?", convos[0].id)) messages.append( Message(users[3].id, datetime.datetime.now(), "Never dumbass LOL", convos[0].id)) messages.append( Message(users[2].id, datetime.datetime.now(), "Why can't you help me?", convos[0].id)) messages.append( Message(users[3].id, datetime.datetime.now(), "Was just joking, send me a meeting request", convos[0].id)) messages.append( Message(users[1].id, datetime.datetime.now(), "Shalom, looks like a prety cool group", convos[1].id)) messages.append( Message(groups[0].id, datetime.datetime.now(), "Yeah I know were pretty sick", convos[1].id)) messages.append( Message(groups[0].id, datetime.datetime.now(), "I don't know how to do problem number 3 from quiz 1", convos[1].id)) messages.append( Message(groups[0].id, datetime.datetime.now(), "Can anyone help me?", convos[1].id)) messages.append( Message(users[1].id, datetime.datetime.now(), "What is this group for?", convos[2].id)) messages.append( Message(users[1].id, datetime.datetime.now(), "Read the BIO!", convos[2].id)) messages.append( Message(users[1].id, datetime.datetime.now(), "What grade did you get in data structures?", convos[3].id)) messages.append( Message(users[0].id, datetime.datetime.now(), "An A-", convos[3].id)) messages.append( Message(users[1].id, datetime.datetime.now(), "Great! Let's schedule a tutoring session", convos[3].id)) messages.append( Message( users[4].id, datetime.datetime.now(), "If anyone needs assistance with their homework 3, shoot me a message", convos[4].id)) #5 messages.append( Message(groups[2].id, datetime.datetime.now(), "I think we all do, can we set up a group tutoring session", convos[4].id)) messages.append( Message( users[6].id, datetime.datetime.now(), "Struggling alot in 445, I saw you recently took that class. Can we set up a tutoring sesson?", convos[5].id)) messages.append( Message(users[7].id, datetime.datetime.now(), "Yes absolutely", convos[5].id)) messages.append( Message(users[6].id, datetime.datetime.now(), "Great! Let's schedule a tutoring session", convos[5].id)) messages.append( Message( users[9].id, datetime.datetime.now(), "Struggling alot in 1501, I saw you recently took that class. Can we set up a tutoring sesson?", convos[6].id)) messages.append( Message(users[8].id, datetime.datetime.now(), "Yes absolutely", convos[6].id)) messages.append( Message(users[9].id, datetime.datetime.now(), "Great! Let's schedule a tutoring session", convos[6].id)) messages.append( Message( users[10].id, datetime.datetime.now(), "Struggling alot in system architecture, I saw you recently took that class. Can we set up a tutoring sesson?", convos[7].id)) messages.append( Message(users[12].id, datetime.datetime.now(), "Yes absolutely", convos[7].id)) messages.append( Message(users[10].id, datetime.datetime.now(), "Great! Let's schedule a tutoring session", convos[7].id)) for x in messages: db.session.add(x) db.session.commit() meeting_reqs = [] meeting_reqs.append( Meeting(str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")), "Cathy", courses[2].id, convos[1].id, users[3].id, None)) meeting_reqs.append( Meeting(str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")), "Benny", courses[2].id, convos[1].id, None, groups[0].id)) meeting_reqs.append( Meeting(str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")), "Hillman", courses[0].id, convos[0].id, users[1].id, None)) meeting_reqs.append( Meeting(str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")), "Market", courses[1].id, convos[2].id, users[1].id, None)) for x in meeting_reqs: db.session.add(x) db.session.commit() contact_req = [] contact_req.append( ContactRequest("Yo yo yo, add me dawg", users[0].id, users[0].id, None, groups[1].id)) contact_req.append( ContactRequest("Hiyah I need a tutor", users[2].id, users[2].id, users[3].id, None)) for x in contact_req: db.session.add(x) db.session.commit()
async def send_notification(self, sender_id=None, event=None, channel_id=None, keyword=None, keyword_id=None, message_obj=None): message_text = message_obj.message # Lets set the meta data is_mention = message_obj.mentioned is_scheduled = message_obj.from_scheduled is_fwd = False if message_obj.fwd_from is None else True is_reply = False if message_obj.reply_to_msg_id is None else True is_bot = False if message_obj.via_bot_id is None else True if isinstance(message_obj.to_id, PeerChannel): is_channel = True is_group = False is_private = False elif isinstance(message_obj.to_id, PeerChat): is_channel = False is_group = True is_private = False else: is_channel = False is_group = False is_private = False # We track the channel size and set it to expire after sometime, if it does we update the participant size if channel_id in self.channel_meta and self.channel_meta[channel_id][ 'channel_size'] == 0 or datetime.now( ) > self.channel_meta[channel_id]['channel_texpire']: logging.info('refreshing the channel information') channel_size = await self.get_channel_user_count(channel_id) else: channel_size = self.channel_meta[channel_id]['channel_size'] # Lets get who sent the message sender = await event.get_sender() sender_username = sender.username channel_id = abs(channel_id) timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Set the message for the notification we're about to send in our monitor channel message = '⚠️ "{}" mentioned by {} in => "{}" url: {}\n\n Message:\n"{}\ntimestamp: {}'.format( keyword, sender_username, self.channel_meta[channel_id]['channel_title'], self.channel_meta[channel_id]['channel_url'], message_text, timestamp) logging.info('{} Sending notification {}'.format( sys._getframe().f_code.co_name, message)) # ---------------- # Send the message # ---------------- await self.client.send_message(self.monitor_channel, message) # ------------------------- # Write to the Google Sheet 写入到谷歌工作表 # ------------------------- '''self.sheet.append_row([ sender_id, sender_username, channel_id, self.channel_meta[channel_id]['channel_title'], self.channel_meta[channel_id]['channel_url'], keyword, message_text, is_mention, is_scheduled, is_fwd, is_reply, is_bot, is_channel, is_group, is_private, channel_size, timestamp ])''' # -------------- # Add user to DB # -------------- o = await self.get_user_by_id(sender_id) self.session = self.Session() if not bool( self.session.query(ChatUser).filter_by( chat_user_id=sender_id).all()): self.session.add( ChatUser(chat_user_id=sender_id, chat_user_is_bot=o['is_bot'], chat_user_is_verified=o['is_verified'], chat_user_is_restricted=o['is_restricted'], chat_user_first_name=o['first_name'], chat_user_last_name=o['last_name'], chat_user_name=o['username'], chat_user_phone=o['phone'], chat_user_tlogin=datetime.now(), chat_user_tmodified=datetime.now())) # ----------- # Add message # ----------- msg = Message(chat_user_id=sender_id, account_id=self.account.account_id, channel_id=channel_id, keyword_id=keyword_id, message_text=message_text, message_is_mention=is_mention, message_is_scheduled=is_scheduled, message_is_fwd=is_fwd, message_is_reply=is_reply, message_is_bot=is_bot, message_is_group=is_group, message_is_private=is_private, message_is_channel=is_channel, message_channel_size=channel_size, message_tcreate=datetime.now()) self.session.add(msg) self.session.flush() message_id = msg.message_id self.session.add( Notification(keyword_id=keyword_id, message_id=message_id, channel_id=channel_id, account_id=self.account.account_id, chat_user_id=sender_id)) # ----------- # Write to DB # ----------- try: self.session.commit() except IntegrityError: pass self.session.close()
def get(self): messages=Message.query().fetch() params={"message_list": messages} return self.render_template("message_list.html", params=params)
def users_show(user_id): """Show user profile.""" user = User.query.get_or_404(user_id) messages = Message.get_filtered_messages([user_id]) return render_template('users/show.html', user=user, messages=messages)
def button_pressed(self, bot, update): query = update.callback_query category: str = query.data message = Message.get_or_none(Message.id == query.message.message_id) inline_ignore_keyboard = InlineKeyboardMarkup([[ InlineKeyboardButton( text='❌', callback_data=self.keywords['ask_again'] ), InlineKeyboardButton( text='❌&🔄', callback_data=self.keywords['ask_again_and_reload'] ), ]]) if message is not None: reload = category == self.keywords['ask_again_and_reload'] ignore_message = category == self.keywords['ignore'] ask_message_again = category == self.keywords['ask_again'] or reload spreadsheet_saving_success = False if message.transaction is not None: if not ignore_message: transaction = message.transaction spreadsheet_saving_success = self.g_sheet.add( amount=transaction.amount, description=transaction.description, category=category, time=transaction.time, is_debit=transaction.is_debit ) elif ask_message_again: message.transaction.asked = False message.transaction.save() else: message.transaction.ignored = True message.transaction.save() if spreadsheet_saving_success or ignore_message or ask_message_again: message.delete_instance() if not bot.delete_message(chat_id=query.message.chat_id, message_id=query.message.message_id): query.edit_message_text( text=query.message.text + ( f'\nChosen category: *{category}* ✔' if not ignore_message or ask_message_again else f'\n*❌ IGNORED ❌' ), parse_mode='Markdown' ) if reload: self.ask_transactions_again(bot, update) elif not spreadsheet_saving_success: query.edit_message_text( text=query.message.text + f'\n❌ *ERROR SAVING TO SPREADSHEET* ❌', parse_mode='Markdown', reply_markup=inline_ignore_keyboard ) else: Message.insert(id=query.message.message_id, transaction_id=-1).execute() query.edit_message_text( text=query.message.text + f'\n❌ *ERROR: UNKNOWN MESSAGE* ❌', parse_mode='Markdown', reply_markup=inline_ignore_keyboard )
def get(self, message_id): message = Message.select().where(Message.id == int(message_id)).get() params = {"message": message} return self.render_template("message_delete.html", params=params)
import sys import os root = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, root) from models import Message import config as config obj = Message() def migrate(): if config.columns: print(obj.alter_table()) else: print(obj.create_all()) migrate()
def create_message_object(self, message): return Imap(date=message['Date'], origin=email.utils.parseaddr(message['From'])[1], subject=message['Subject']) def get_messages_by_body_subject(self, word): collection = [ self.create_message_object(self.fetch_message(i)) for i in self.get_messages_list(word) ] return collection if __name__ == '__main__': obj = Imap() messages = obj.get_messages_by_body_subject('devops') for m in messages: try: mess = Message() data = parser.parse(m.get_date()) mess.date = data mess.origin = m.get_origin() mess.origin = m.get_subject() session.add(mess) session.commit() except Exception as e: print(e)