Example #1
0
 def post(self, request, format=None):
     serializer = ActivityPostSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         messages.send_message(serializer.data)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #2
0
def new_message(request, template):
    """Send a new private message."""
    to = request.GET.get('to')
    if to:
        try:
            User.objects.get(username=to)
        except User.DoesNotExist:
            contrib_messages.add_message(
                request, contrib_messages.ERROR,
                _('Invalid username provided. Enter a new username below.'))
            return HttpResponseRedirect(reverse('messages.new'))

    form = MessageForm(request.POST or None, initial={'to': to})

    if request.method == 'POST' and form.is_valid():
        send_message(form.cleaned_data['to'], form.cleaned_data['message'],
                     request.user)
        if form.cleaned_data['in_reply_to']:
            irt = form.cleaned_data['in_reply_to']
            try:
                m = InboxMessage.objects.get(pk=irt, to=request.user)
                m.update(replied=True)
            except InboxMessage.DoesNotExist:
                pass
        contrib_messages.add_message(request, contrib_messages.SUCCESS,
                                     _('Your message was sent!'))
        return HttpResponseRedirect(reverse('messages.inbox'))

    return render(request, template, {'form': form})
def client_send_message(client_socket, message):
    """
    Send a message and try to get a receive
    """
    messages.send_message(client_socket, message)
    message = messages.read_message(client_socket)
    echo("[Client] Received: %s", message)
Example #4
0
def talk_to_me():
    if request.method == 'GET':
        return render_template('talk_to_me.html')
    else:
        msg = ''
        m_user = request.form.get('m_user')
        m_secret = request.form.get('m_secret')
        guy = request.form.get('guy')
        message = request.form.get('message')
        m_list = request.form.get('m_list')

        user = request.form.get('user')
        secret = request.form.get('secret')
        new_password = request.form.get('new_password')
        listing = request.form.get('list')
        delete = request.form.get('deletion')

        print(m_user, m_secret, guy, message, m_list)
        print(user, secret, new_password, listing, delete)

        if delete == 'yes':
            u.delete_user(user, secret)
        if listing == 'yes':
            u.list_users()
        if m_list == 'yes':
            m.list_messages(m_user, m_secret)
        if message is not None:
            m.send_message(m_user, m_secret, guy, message)
        if user is not None:
            u.create_user(user, secret)
        if new_password is not None:
            u.edit_user(user, secret, new_password)

        return render_template('talk_to_me.html', msg=msg)
Example #5
0
def new_message(request, template):
    """Send a new private message."""
    to = request.GET.get('to')
    if to:
        try:
            User.objects.get(username=to)
        except User.DoesNotExist:
            contrib_messages.add_message(
                request, contrib_messages.ERROR,
                _('Invalid username provided. Enter a new username below.'))
            return HttpResponseRedirect(reverse('messages.new'))

    form = MessageForm(request.POST or None, initial={'to': to})

    if request.method == 'POST' and form.is_valid():
        send_message(form.cleaned_data['to'], form.cleaned_data['message'],
                     request.user)
        if form.cleaned_data['in_reply_to']:
            irt = form.cleaned_data['in_reply_to']
            try:
                m = InboxMessage.objects.get(pk=irt, to=request.user)
                m.update(replied=True)
            except InboxMessage.DoesNotExist:
                pass
        contrib_messages.add_message(request, contrib_messages.SUCCESS,
                                     _('Your message was sent!'))
        return HttpResponseRedirect(reverse('messages.inbox'))

    return render(request, template, {'form': form})
Example #6
0
    def save_character(self, form):

        redis = self.redis
        character = self.character

        old_acronym = character['acronym']
        old_name = character['name']
        old_color = character['color']

        # Truncate acronym to 15 characters.
        character['acronym'] = form['acronym'][:15]

        # Validate name
        if len(form['name'])>0:
            # Truncate name to 50 characters.
            character['name'] = form['name'][:50]
        else:
            raise ValueError("name")

        # Validate colour
        if re.compile('^[0-9a-fA-F]{6}$').search(form['color']):
            character['color'] = form['color']
        else:
            raise ValueError("color")

        character['quirk_prefix'] = form['quirk_prefix']

        # Validate case
        if form['case'] in CASE_OPTIONS.keys():
            character['case'] = form['case']
        else:
            raise ValueError("case")

        replacements = zip(form.getlist('quirk_from'), form.getlist('quirk_to'))
        # Strip out any rows where from is blank or the same as to.
        replacements = [_ for _ in replacements if _[0]!='' and _[0]!=_[1]]
        # And encode as JSON.
        character['replacements'] = json.dumps(replacements)

        saved_character = dict(character)
        pipe = redis.pipeline()
        pipe.delete(self.prefix)
        pipe.hmset(self.prefix, saved_character)
        pipe.execute()

        # Chat-related things.
        if self.chat is not None:
            if character['name']!=old_name or character['acronym']!=old_acronym:
                if self.meta['group']=='silent':
                    user_change_message = None
                else:
                    user_change_message = '%s [%s] is now %s [%s].' % (old_name, old_acronym, character['name'], character['acronym'])
                send_message(redis, request.form['chat'], -1, 'user_change', user_change_message)
            elif character['color']!=old_color:
                send_message(redis, request.form['chat'], -1, 'user_change', None)
def run(name, number, pickup=None):
    new_id = set_info.add_person(name, number, pickup)
    person = get_info.get_person_by_id(new_id)
    welcome_message = "Hi! I'm the GLMC Ride coordinator bot! "
    welcome_message += "Nice to meet you, {} :) ".format(person.get_name())
    welcome_message += "I'll be messaging you weekly to see if you're coming "
    welcome_message += "to GLMC, so make sure to save my number in your contacts! "
    welcome_message += "I'm just a bot, so if you have any big questions, make sure "
    welcome_message += "to contact Zach instead at (626) 377-8839. See ya later!"
    messages.send_message(person, welcome_message)
    chuck_norris_message = "oh also, if you text me the word 'chuck', I'll tell you a "
    chuck_norris_message += "Chuck Norris joke"
    messages.send_message(person, chuck_norris_message)
Example #8
0
def msgbox_keypress(widge,event):
    #Handles keypresses - for example when user presses enter to send a message
    logging.debug(event.keyval)
    gm = transport_select.get_model()
    ta = transport_select.get_active_iter()
    if(ta != None): print(gm.get_value(ta,0))
    if(event.keyval == 65293 and contacts.Selected > -1):
          messages.send_message(contacts.Selected,"lan",None,sb.get_text())
          sb.set_text("")

    elif(event.keyval == 65293 and sb.get_text()[:1] == "#"):
        tp.send_bcast("lan","",sb.get_text()[1:])
        sb.set_text("")
    def server_connection_thread_target(connection_socket, address):
        """
        Client-Server message loop. Just receiving messages and echoing back to the client.
        Special message "Bye" closes the connection
        WARNING: we assume that clients don't abuse the connection, i.e a client should end the connection, not the server
        """
        can_send = True

        try:

            while True:
                # reading one message from the client
                message = messages.read_message(connection_socket)
                if message is None:
                    # message is None, that means that the client has stopped sending data to the server
                    echo("[Server] Got EOF from Client")
                    # in that case we can shutdown reading
                    connection_socket.shutdown(socket.SHUT_RD)

                    # lets check if the server shut down sending first
                    if can_send:
                        # send bye message to the client ...
                        messages.send_message(connection_socket, "Bye bye Client")
                        # ... and shut down sending
                        connection_socket.shutdown(socket.SHUT_WR)

                    # nothing to send, nothing to receive, we can leave the message loop now
                    break

                echo("[Server] Received [%s]: %s", address, message)

                # lets check if the server can send messages
                if can_send:
                    # echoing message from the client
                    messages.send_message(connection_socket, message)

                    # if we received special message from the client
                    if message == "Bye":
                        # shut down sending to the client and start only to listen for the remaining client messages
                        connection_socket.shutdown(socket.SHUT_WR)
                        can_send = False

        except Exception:
            echo("[Server] Connection error")
        finally:
            echo("[Server] Closing socket")
            # close the socket
            connection_socket.close()
Example #10
0
def post_message():
    from_member_id = request.get_header('userToken')
    subject = request.json['subject']
    message_contents = request.json['messageContents']
    messageType = request.json['messageType']
    retObj = {}

    if messageType == 'single':
        to_member_id = request.json['toMemberId']
        message_id = messages.send_message(from_member_id, to_member_id, subject, message_contents)
        retObj = {"messageId": message_id}
    elif messageType == 'broadcast':

        start_time = time.time()

        if request.get_header('DD-Process-Type') == 'simple':
            message_id = messages.send_broadcast_thinDatabase(from_member_id, subject, message_contents)
        else:
            message_id = messages.send_broadcast_thickDatabase(from_member_id, subject, message_contents)

        retObj = {"messageCount": message_id,
                  "executionTime":(time.time() - start_time)}

    response.status = 201
    return retObj
Example #11
0
def post_message():
    from_member_id = request.get_header('userToken')
    subject = request.json['subject']
    message_contents = request.json['messageContents']
    messageType = request.json['messageType']
    retObj = {}

    if messageType == 'single':
        to_member_id = request.json['toMemberId']
        message_id = messages.send_message(from_member_id, to_member_id,
                                           subject, message_contents)
        retObj = {"messageId": message_id}
    elif messageType == 'broadcast':

        start_time = time.time()

        if request.get_header('DD-Process-Type') == 'simple':
            message_id = messages.send_broadcast_thinDatabase(
                from_member_id, subject, message_contents)
        else:
            message_id = messages.send_broadcast_thickDatabase(
                from_member_id, subject, message_contents)

        retObj = {
            "messageCount": message_id,
            "executionTime": (time.time() - start_time)
        }

    response.status = 201
    return retObj
Example #12
0
def add_comment(match_id):
    if request.method == "GET":
        return redirect("/")
    if request.method == "POST":
        message = request.form["message"]
        session["message"] = message
        if len(message) < 1:
            flash("Tyhjä kenttä")
        if len(message) > 500:
            flash("Liian pitkä viesti")
        if session["csrf_token"] != request.form["csrf_token"]:
            abort(403)
        messages.send_message(match_id, message)
        list = matches.refresh_match_page(match_id)
        return render_template("matchpage.html",
                               match=list[0],
                               messages=list[1])
Example #13
0
def new_message(request):
    form = MessageForm(request.POST or None)

    if request.method == 'POST' and form.is_valid():
        send_message(form.cleaned_data['to'], form.cleaned_data['message'],
                     request.user)
        if form.cleaned_data['in_reply_to']:
            irt = form.cleaned_data['in_reply_to']
            try:
                m = InboxMessage.objects.get(pk=irt, to=request.user)
                m.update(replied=True)
            except InboxMessage.DoesNotExist:
                pass
        contrib_messages.add_message(request, contrib_messages.SUCCESS,
                                     _('Your message was sent!'))
        return HttpResponseRedirect(reverse('messages.inbox'))

    return jingo.render(request, 'messages/new.html', {'form': form})
Example #14
0
def new_message(request):
    form = MessageForm(request.POST or None)

    if request.method == 'POST' and form.is_valid():
        send_message(form.cleaned_data['to'], form.cleaned_data['message'],
                     request.user)
        if form.cleaned_data['in_reply_to']:
            irt = form.cleaned_data['in_reply_to']
            try:
                m = InboxMessage.objects.get(pk=irt, to=request.user)
                m.update(replied=True)
            except InboxMessage.DoesNotExist:
                pass
        contrib_messages.add_message(request, contrib_messages.SUCCESS,
                                     _('Your message was sent!'))
        return HttpResponseRedirect(reverse('messages.inbox'))

    return jingo.render(request, 'messages/new.html', {'form': form})
Example #15
0
    def start(self, projectname):
        dataMap = self.get_settings()
        current_directory = os.getcwd()
        data_folder = Path("osdp")
        file_to_open = data_folder / "projects" / dataMap['osdp'][
            'project'] / dataMap['osdp']['platform']
        self.final_directory = os.path.join(current_directory, file_to_open)
        if not os.path.exists(self.final_directory):
            print("This should have already been created")
            self.build()
        if dataMap['osdp']['platform'] == 'vagrant':
            messages.send_message(
                dataMap['osdp']['username'] + " " +
                "Just started a vagrant box for Python Development")
            vagrant_folder = Path(self.final_directory)
            v = vagrant.Vagrant(vagrant_folder, quiet_stdout=False)
            try:
                v.up()
            except Exception as e:
                print("Please open a github issue if you have a problem")
            os.chdir(vagrant_folder)
            cmdCommand = "vagrant port"
            process = subprocess.Popen(cmdCommand.split(),
                                       stdout=subprocess.PIPE)
            output, error = process.communicate()
            print(output)
            subprocess.run(["vagrant", "ssh"])
        elif dataMap['osdp']['platform'] == 'docker':
            print("Ths platform is docker and we will connect to the image")
            os.chdir(self.final_directory)
            retval = os.getcwd()
            IMG_SRC = dataMap['osdp']['dockerdeveloperimage']
            client = docker.Client()
            # Uncomment if working with a private image
            #client.login(username=dataMap['osdp']['dockerhubusername'], password=dataMap['osdp']['dockerhubpassword'], registry="https://index.docker.io/v1/")
            client.pull(IMG_SRC)
            #client.tag(image=dataMap['osdp']['dockerdeveloperimage'], repository=dataMap['osdp']['pushto'],tag=dataMap['osdp']['runtime'])
            #response = [line for line in client.push(dataMap['osdp']['pushto'] + ":" + dataMap['osdp']['runtime'], stream=True)]
            container_id = client.create_container(dataMap['osdp']['imagename'],stdin_open=True,tty=True,command='/bin/bash', volumes=dataMap['osdp']['dockerhome'],host_config=client.create_host_config \
            # Need to adjust this for mac users - change /Users to /home

            (binds=[dataMap['osdp']['dockerhome'] + ':' + '/home',]))
            #(binds=['/home:/home',]))
            dockerpty.start(client, container_id)
Example #16
0
    def test_send_message(self):
        to = [user(save=True), user(save=True)]
        sender = user(save=True)
        msg_text = "hi there!"
        send_message(to=to, text=msg_text, sender=sender)

        msgs_in = InboxMessage.objects.all()
        msgs_out = OutboxMessage.objects.all()
        eq_(1, msgs_out.count())
        msg_out = msgs_out[0]
        eq_(sender, msg_out.sender)
        eq_(msg_text, msg_out.message)
        for u in msg_out.to.all():
            assert u in to
        eq_(2, msgs_in.count())
        for message in msgs_in:
            eq_(sender, message.sender)
            assert message.to in to
            eq_(msg_text, message.message)
Example #17
0
def post_message():
    from_member_id = request.get_header('userToken')
    to_member_id = request.json['toMemberId']
    subject = request.json['subject']
    message_contents = request.json['messageContents']

    message_id = messages.send_message(from_member_id, to_member_id, subject, message_contents)

    response.status = 201
    return {"messageId": message_id}
Example #18
0
    def test_send_message(self):
        to = [get_user('jsocol'), get_user('pcraciunoiu')]
        sender = get_user('rrosario')
        msg_text = "hi there!"
        send_message(to=to, text=msg_text, sender=sender)

        msgs_in = InboxMessage.objects.all()
        msgs_out = OutboxMessage.objects.all()
        eq_(1, msgs_out.count())
        msg_out = msgs_out[0]
        eq_(sender, msg_out.sender)
        eq_(msg_text, msg_out.message)
        for user in msg_out.to.all():
            assert user in to
        eq_(2, msgs_in.count())
        for message in msgs_in:
            eq_(sender, message.sender)
            assert message.to in to
            eq_(msg_text, message.message)
    def test_send_message(self):
        to = [user(save=True), user(save=True)]
        sender = user(save=True)
        msg_text = "hi there!"
        send_message(to=to, text=msg_text, sender=sender)

        msgs_in = InboxMessage.objects.all()
        msgs_out = OutboxMessage.objects.all()
        eq_(1, msgs_out.count())
        msg_out = msgs_out[0]
        eq_(sender, msg_out.sender)
        eq_(msg_text, msg_out.message)
        for u in msg_out.to.all():
            assert u in to
        eq_(2, msgs_in.count())
        for message in msgs_in:
            eq_(sender, message.sender)
            assert message.to in to
            eq_(msg_text, message.message)
Example #20
0
def post_message():
    from_member_id = request.get_header('userToken')
    to_member_id = request.json['toMemberId']
    subject = request.json['subject']
    message_contents = request.json['messageContents']

    message_id = messages.send_message(from_member_id, to_member_id, subject,
                                       message_contents)

    response.status = 201
    return {"messageId": message_id}
Example #21
0
def test_default():
    messages.db.delete('messages', where='to_userid=2')
    msgid = messages.send_message(1, 2, 'test message')

    msg = messages.get_message(msgid)
    assert msg.content == 'test message'

    msgs = messages.get_messages(2)
    assert len(list(msgs)) == 1

    messages.read_message(msgid)
    msg = messages.get_message(msgid)
    assert msg.unread == 0
Example #22
0
 def save_data(self):
     logger.info(f"current row {self.get_current_data(self.date)}")
     logger.info(f"date {self.date}")
     logger.info(f"local date {self.date_local_tz}")
     datetime_object = datetime.strptime(self.date, '%Y-%m-%dT%H:%M:%SZ')
     datetime_object_local = datetime.strptime(self.date_local_tz,
                                               '%Y-%m-%dT%H:%M:%S%z')
     logger.info(f"datetime object {datetime_object}")
     logger.info(f"datetime local {datetime_object_local}")
     if not self.get_current_data(self.date):
         send_new_alert = self.alert_send_check()
         if send_new_alert[0]:
             messages.send_message(send_new_alert[1], CFG.TO_NUMBERS)
         saved_row = db.add_data(
             datetime_object, self.hour_num, self.min_num,
             self.settlement_point, self.price_type, self.price_ckwh,
             self.value_score, self.mean_price_ckwh, self.diff_mean_ckwh,
             self.high_ckwh, self.low_ckwh, self.std_dev_ckwh,
             self.price_display, self.price_display_sign,
             datetime_object_local)
         logger.info(f"saved data {saved_row}")
     else:
         logger.info(f"row exists")
def client2(address):

    # creating socket ...
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # ... and connecting to the server
    client_socket.connect(address)

    # send hello message and receive echo
    client_send_message(client_socket, "Hello")

    # send bye message
    client_send_message(client_socket, "Bye")
    # the server should sent EOF
    if messages.read_message(client_socket) is None:
        echo("[Client] Got EOF from server")

        # shutting down read
        client_socket.shutdown(socket.SHUT_RD)
        # sending bye message to the server
        messages.send_message(client_socket, "Bye bye Server")
        messages.send_message(client_socket, "Have a good day")
        client_socket.shutdown(socket.SHUT_WR)

    client_socket.close()
Example #24
0
    def save_character(self, form):

        redis = self.redis
        character = self.character

        old_acronym = character.get('acronym', '')
        old_name = character.get('name', '')
        old_color = character.get('color', '000000')

        # Truncate acronym to 15 characters.
        character['acronym'] = form['acronym'][:15]

        # Validate name
        if len(form['name'])>0:
            # Truncate name to 50 characters.
            character['name'] = form['name'][:50]
        else:
            raise ValueError("name")

        # Validate colour
        if re.compile('^[0-9a-fA-F]{6}$').search(form['color']):
            character['color'] = form['color']
        else:
            raise ValueError("color")

        # Validate character
        # XXX Get all-chars from CHARACTER_DEFAULTS.keys()?
        if form['character'] in redis.smembers('all-chars'):
            character['character'] = form['character']
        else:
            raise ValueError("character")

        character['quirk_prefix'] = form['quirk_prefix']
        character['quirk_suffix'] = form['quirk_suffix']

        # Validate case
        if form['case'] in CASE_OPTIONS.keys():
            character['case'] = form['case']
        else:
            raise ValueError("case")

        replacements = zip(form.getlist('quirk_from'), form.getlist('quirk_to'))
        # Strip out any rows where from is blank or the same as to.
        replacements = [_ for _ in replacements if _[0]!='' and _[0]!=_[1]]
        # And encode as JSON.
        character['replacements'] = json.dumps(replacements)

        saved_character = dict(character)
        for key, value in CHARACTER_DETAILS[character['character']].items():
            if saved_character[key]==value:
                del saved_character[key]
        pipe = redis.pipeline()
        pipe.delete(self.prefix)
        pipe.hmset(self.prefix, saved_character)
        pipe.execute()

        # Chat-related things.
        if self.chat is not None:
            redis.sadd('chat.'+self.chat+'.characters', character['character'])
            if character['name']!=old_name or character['acronym']!=old_acronym:
                if self.meta['group']=='silent':
                    user_change_message = None
                else:
                    user_change_message = '%s [%s] is now %s [%s]. ~~ %s ~~' % (old_name, old_acronym, character['name'], character['acronym'], self.meta['counter'])
                send_message(redis, request.form['chat'], -1, 'user_change', user_change_message)
            elif character['color']!=old_color:
                send_message(redis, request.form['chat'], -1, 'user_change', None)
Example #25
0
 parser.add_argument("--destroyall","-x", required=False,dest='destroyall',action='store_true',help='Destroy all running vagrant boxes')
 parser.add_argument("--dockerps","-ps", required=False,dest='dockerps',action='store_true',help='Gives the status of all running docker containers')
 parser.add_argument("--dropbox","-db", required=False,dest='dropbox',action='store_true',help='Does an rsync to your Dropbox folder')
 parser.add_argument("--killserver","-k", required=False,dest='killserver',action='store_true',help='Kill local server')
 parser.add_argument("--add","-a", required=False,dest='add',action='store',help='Add project from team server')
 parser.add_argument("--connect","-o", required=False,dest='connect',action='store',help='Connect to your kubernetes IDE')
 parser.add_argument("--delete","-t", required=False,dest='delete',action='store',help='Delete project from API')
 # run in server mode only
 parser.add_argument("--server","-p", required=False,dest='server',action='store_true',help='Start server mode')
 result = parser.parse_args()

 if result.init:
     logger.info("Pulling down yaml file so you can customize your environment!")
     #print("Pulling down yaml file so you can customize your development environment.")
     test.init()
     messages.send_message("User just initialized a new project")
 elif result.build:
     test.build()
 elif result.update:
     test.update()
 elif result.backup:
     logger.info("We are backing up all your projects to S3!")
     test.backup_to_S3()
 elif result.destroy:
     project = result.destroy
     logger.info("We are destroying your vagrant box now!")
     #print("We are destroying your vagrant box and removing your project folder.")
     test.destroy(projectname=project)
 elif result.start:
     project = result.start
     logger.info("We are starting your development environment now!")
def alert_about_new_dogs(new_dogs):
    for dog in new_dogs:
        print(dog)
        messages.send_message("Adopt A Pet", dog['name'], dog['gender'],
                              dog['age'], dog['image'])
Example #27
0
def alert_about_new_dogs(new_dogs):
    for dog in new_dogs:
        print(dog)
        messages.send_message("Freedom Dog Rescue", dog['info'], dog['image'],
                              '', '')
Example #28
0
    def build(self):
        try:
            if not os.path.isfile('osdp/configuration/settings.yml'):
                print(
                    "You ran new before init so let me grab the files for you")
                self.init()
                sys.exit(1)
        except:
            pass

        dataMap = self.get_settings()
        self.check_settings(dataMap)
        current_directory = os.getcwd()
        data_folder = Path("osdp")
        if dataMap['osdp']['platform'] == 'vagrant':
            file_to_open = data_folder / "projects" / dataMap['osdp'][
                'project'] / "vagrant"
            self.final_directory = os.path.join(current_directory,
                                                file_to_open)
        elif dataMap['osdp']['platform'] == 'docker':
            file_to_open = data_folder / "projects" / dataMap['osdp'][
                'project'] / "docker"
            self.final_directory = os.path.join(current_directory,
                                                file_to_open)
        elif dataMap['osdp']['platform'] == 'kubernetes':
            file_to_open = data_folder / "projects" / dataMap['osdp'][
                'project'] / "kubernetes"
            self.final_directory = os.path.join(current_directory,
                                                file_to_open)
        if os.path.exists(self.final_directory):
            self.logger.info("A project with that name already exists!")
            self.logger.info(
                "We will remove the folder but the api is for teams and will be remain intact"
            )
            try:
                self.get_project_from_db(dataMap['osdp']['project'])
            except:
                self.logger.info(
                    "This settings file has not been pushed to the api yet")
            #self.backup_to_S3()
            self.remove_project_folder(dataMap)
        else:
            os.makedirs(self.final_directory)
        url = dataMap['osdp']['github']
        #url = "https://github.com/" + dataMap['osdp']['username'] + "/" + dataMap['osdp']['linux'] + ".git"
        self.logger.info("Downloading project files!")
        try:
            Repo.clone_from(url, self.final_directory, branch="master")
        except git.exc.GitCommandError as e:
            self.logger.info(
                "The folder already exists with that project name. Try python3 teamdev.py --start projectname"
            )
            #self.remove_project_folder(dataMap)
            sys.exit(1)
        try:
            #print(dataMap)
            self.save_to_db(dataMap)
        except:
            self.logger.info("Could not save to db through api")
        self.get_project_from_db(dataMap['osdp']['project'])
        if dataMap['osdp']['platform'] == 'docker':
            IMG_SRC = dataMap['osdp']['dockerdeveloperimage']
            client = docker.Client()
            #client.login(username=dataMap['osdp']['dockerhubusername'], password=dataMap['osdp']['dockerhubpassword'], registry="https://index.docker.io/v1/")
            client.pull(IMG_SRC)
            #client.tag(image=dataMap['osdp']['dockerdeveloperimage'], repository=dataMap['osdp']['pushto'],tag=dataMap['osdp']['runtime'])
        messages.send_message(dataMap['osdp']['username'] + " " +
                              "Just created a new" + " " +
                              dataMap['osdp']['platform'] + " " +
                              "Development Environment")
Example #29
0
def alert_about_new_dogs(new_dogs):
    for dog in new_dogs:
        print(dog)
        messages.send_message("Ottawa Humane Society", dog['name'],
                              dog['gender'], dog['age'], dog['image'])
Example #30
0
def main():
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(help='commands', dest='command')

    # Accounts command
    account_parser = subparsers.add_parser('account',
                                           help='Runs account examples')
    account_parser.add_argument('--get',
                                '-g',
                                default=False,
                                action='store_true',
                                help='Get account resource')
    account_parser.add_argument('--update',
                                '-u',
                                default=False,
                                action='store_true',
                                help='Upate account resource')
    account_parser.add_argument('--billing-status',
                                '-s',
                                default=False,
                                action='store_true',
                                help='Get account billing status')
    account_parser.add_argument('--id',
                                '-i',
                                required=False,
                                type=str,
                                action='store',
                                help='Resource id')
    account_parser.add_argument('--company-name',
                                '-n',
                                required=False,
                                type=str,
                                action='store',
                                help='Company name')

    # Users command
    users_parser = subparsers.add_parser('user', help='Runs user examples')
    users_parser.add_argument('--list',
                              '-l',
                              default=False,
                              action='store_true',
                              help='Lists users associated with your account')
    users_parser.add_argument('--get',
                              '-g',
                              default=False,
                              action='store_true',
                              help='Get user resource')
    users_parser.add_argument('--id',
                              '-i',
                              required=False,
                              type=str,
                              action='store',
                              help='Resource id')

    # Mesages command
    messages_parser = subparsers.add_parser('message',
                                            help='Runs messages example')
    messages_parser.add_argument('--list',
                                 '-l',
                                 default=False,
                                 action='store_true',
                                 help='Lists message resources')
    messages_parser.add_argument('--send',
                                 '-s',
                                 default=False,
                                 action='store_true',
                                 help='Send message')
    messages_parser.add_argument('--get',
                                 '-g',
                                 default=False,
                                 action='store_true',
                                 help='Get message resource')
    messages_parser.add_argument('--id',
                                 '-i',
                                 required=False,
                                 type=str,
                                 action='store',
                                 help='Resource id')
    messages_parser.add_argument('--body',
                                 '-b',
                                 required=False,
                                 type=str,
                                 action='store',
                                 help='Message body')
    messages_parser.add_argument('--media-url',
                                 '-u',
                                 required=False,
                                 type=str,
                                 action='store',
                                 help='Media URL for MMS')
    messages_parser.add_argument('--from-number',
                                 '-f',
                                 required=False,
                                 type=str,
                                 action='store',
                                 help='From phone number (+12123456789)')
    messages_parser.add_argument('--to-number',
                                 '-t',
                                 required=False,
                                 type=str,
                                 action='store',
                                 help='To phone number (+12128765432)')

    # Number command
    number_parser = subparsers.add_parser('number',
                                          help='Runs number examples')
    number_parser.add_argument('--list-available',
                               '-a',
                               default=False,
                               action='store_true',
                               help='Lists available numbers')
    number_parser.add_argument('--list-associated',
                               '-l',
                               default=False,
                               action='store_true',
                               help='Lists associated numbers')
    number_parser.add_argument('--buy',
                               '-b',
                               default=False,
                               action='store_true',
                               help='Buy number')
    number_parser.add_argument('--update',
                               '-u',
                               default=False,
                               action='store_true',
                               help='Update number')
    number_parser.add_argument('--id',
                               '-i',
                               required=False,
                               type=str,
                               action='store',
                               help='Resource id')
    number_parser.add_argument('--phone-number-name',
                               '-n',
                               required=False,
                               type=str,
                               action='store',
                               help='Phone number name')
    number_parser.add_argument('--phone-number',
                               '-p',
                               required=False,
                               type=str,
                               action='store',
                               help='Phone number (+12124567890)')

    args = parser.parse_args()

    if args.command == 'message':
        if args.send:
            # https://imgs.xkcd.com/comics/lisp_cycles.png
            message = send_message(
                to_number=args.to_number,
                from_number=args.from_number,
                body=args.body,
                media_urls=[args.media_url] if args.media_url else None)
            print(message.id, message.from_number, message.to_number)
        if args.get:
            message = get_message(args.id)
            print(message.id, message.from_number, message.to_number,
                  message.body)
        if args.list:
            for message in list_messages():
                print(message.id, message.to_number, message.from_number,
                      message.body)

    elif args.command == 'number':
        if args.list_available:
            for number in list_available_numbers():
                print(number.name, number.phone_number_type,
                      number.phone_number)
        if args.list_associated:
            for number in list_associated_numbers():
                print(number.id, number.name, number.phone_number_type,
                      number.phone_number)
        if args.buy:
            area_code = args.phone_number[2:5] if args.phone_number.startswith('+') \
                else args.phone_number[1:4]
            number = buy_number(name=args.phone_number_name,
                                phone_number=args.phone_number,
                                area_code=area_code,
                                phone_number_type='local')
            print(number.id, number.name, number.phone_number)
        if args.update:
            number = update_number_name(args.id, name=args.phone_number_name)
            print(number.id, number.name, number.phone_number)
    elif args.command == 'user':
        if args.list:
            for user in list_users():
                print(user.id, user.first_name, user.last_name)
        if args.get:
            user = get_user(args.id)
            print(user.id, user.first_name, user.last_name)
    elif args.command == 'account':
        if args.billing_status:
            status = billing_status()
            print(status)
        if args.get:
            account = get_account(args.id)
            print(account.id, account.company_name)
        if args.update:
            account = update_account(args.id, company_name=args.company_name)
            print(account.id, account.company_name)
Example #31
0
def send_message():
    user = session.get("user")
    message = request.form["message"]
    room_id = request.form["room"]
    messages.send_message(user, message, room_id)
    return redirect("/")
Example #32
0
import ads
import db_utils
import messages


BOT_ID = 'bot1111111111:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'

TOWNS = {
         'brest': ['1', '23.641487,52.021919,23.787812,52.158843', 'CHAT_ID'],
         'gomel': ['2', '30.881999,52.390761,31.051750,52.490685', 'CHAT_ID'],
         'grodno': ['3', '23.766091,53.606835,23.963845,53.726724', 'CHAT_ID'],
         'mogilev': ['4', '30.229468,53.833438,30.399001,53.970047', 'CHAT_ID'],
         'vitebsk': ['6', '30.089889,55.125103,30.306854,55.268390', 'CHAT_ID'],
         'minsk': ['7', '27.397665,53.814539,27.696236,53.980569', 'CHAT_ID']}

connection = connect(host="db", database="ads", user="******", password="******")


for town in TOWNS:
    req_url = 'https://cre-api.kufar.by/ads-search/v1/engine/v1/search/raw?' \
              f'sort=lst.d&size=30&cat=1010&typ=let&rnt=1&rgn={TOWNS[town][0]}' \
              f'&gbx=b:{TOWNS[town][1]}'

    json_response = ads.get_json_response(req_url)
    ad_list = ads.get_ads(json_response)
    unique_ads = db_utils.pg_connect(connection, ad_list, town)

    messages.send_message(unique_ads, town)
    sleep(1)
    print("done")