示例#1
0
def callbackHandler(bot, update, chat_data):
    callbackquery = update.callback_query
    querydata = callbackquery.data
    Tracking.delete_by_id(querydata)
    #bot.answer_callback_query(callbackquery,text="ok 2")
    #update.message.reply_text('Vale')
    update.callback_query.answer('Now your language is')
示例#2
0
def addTracking(bot, update, args, chat=None):
    if len(args) < 1:
        bot.reply(update, "Use /sub username1 username2 username3 ...")
        return
    amazonItems = args
    not_found = []
    already_subscribed = []
    successfully_subscribed = []

    tg_user = update.message.chat_id
    if User.select().where(User.telegramId == tg_user).count() == 0:
        User.create(telegramId=tg_user)

    userdb = User.select().where(User.telegramId == tg_user).get()

    for item in amazonItems:
        Tracking.create(user=userdb.id, asin=item, status='active')

    reply = "OK"

    if len(not_found) is not 0:
        reply += "Sorry, I didn't find username{} {}\n\n".format(
            "" if len(not_found) is 1 else "s", ", ".join(not_found))

    if len(already_subscribed) is not 0:
        reply += "You're already subscribed to {}\n\n".format(
            ", ".join(already_subscribed))

    if len(successfully_subscribed) is not 0:
        reply += "I've added your subscription to {}".format(
            ", ".join(successfully_subscribed))

    bot.send_message(chat_id=update.message.chat_id, text=reply)
示例#3
0
def GetTrackingSavedInfo(pRefParcel):
    ''' Get Tracking info from DB '''
    #Define our connection string
    conn_string = "host='localhost' dbname='vido' user='******' password=''"
    # print the connection string we will use to connect
    print("Connecting to database -> %s" % conn_string)
    # get a connection, if a connect cannot be made an exception will be raised here
    conn = psycopg2.connect(conn_string)
    # conn.cursor will return a cursor object, you can use this cursor to perform queries
    cursor = conn.cursor()
    # 声明一个包裹追踪实例,把数据库中的相关包裹记录都放在这个实例中
    cModelTrack = ModelTrack(pRefParcel, "")
    if pRefParcel is not None:
        sql_str = " SELECT * FROM polls_tracking WHERE tracking_reference = '" + pRefParcel + "'"
        #print(sql_str)
        # Execute our query
        cursor.execute(sql_str)
        # Retrieve the records from the database
        rows = cursor.fetchall()
        for row in rows:
            newTrack = Tracking(row[3], row[4], row[5])
            #print("ref:  " + row[1] + ", date: " + str(row[3]) + ", status: " + row[4] + ", location: " + row[5])
            cModelTrack.addTracking(newTrack)
    cursor.close()
    conn.close()
    return cModelTrack
示例#4
0
    def run(self, reference):
        conn = http.client.HTTPConnection("www.laposte.fr")
        conn.request("GET",
                     "/particulier/outils/suivre-vos-envois?code=" + reference)
        r1 = conn.getresponse()
        print(r1.status, r1.reason)
        data1 = r1.read()
        print(len(data1))
        #logging.debug(str(data1,'utf-8'))
        # 1. 先找出记录表格;2. 然后逐条提取每行记录。
        epTable = re.compile('(<table.*?>(.+?)Résultats pour(.+?)</table>)',
                             re.IGNORECASE)
        epLine = re.compile('<p class="h5">((.|\w)*?)</p>', re.IGNORECASE)
        #result = ep.match(str(data1, 'utf-8'))
        eReference = re.compile(
            'Envoi n° ([A-Z]{2}[0-9]{9}[A-Z]{2}) - Colissimo', re.IGNORECASE)
        eDestination = re.compile('Destination :((\s|[a-zA-Z])+)<',
                                  re.IGNORECASE)
        tabBlock = re.findall(epTable, str(data1, 'utf-8'))
        if (tabBlock is not None):
            #print(tabBlock[0])
            tabBlockStr = tabBlock[0][0]
            #print(tabBlockStr)
            #print(type(tabBlockStr))
            lineBlock = re.findall(epLine, tabBlockStr)
            if (lineBlock is None):
                logging.debug("Can't capture line from table result")
                return
            item = 0

            # 匹配包裹号
            parcelReference = re.findall(eReference, str(data1, 'utf-8'))
            if (parcelReference is not None):
                #print("reference: " + parcelReference[0])
                parcelReference = parcelReference[0].strip()

            # 匹配出收件城市
            parcelCity = re.findall(eDestination, str(data1, 'utf-8'))
            if (parcelCity is not None):
                parcelCity = parcelCity[0][0].strip()
                #print('Location: ' + parcelCity)

            cModelTrack = ModelTrack(parcelReference, parcelCity)
            for index in range(0, int(round(len(lineBlock) / 3))):
                lineNumber = index * 3
                parcelDate = lineBlock[lineNumber][0]
                parcelStatut = lineBlock[lineNumber + 1][0]
                parcelLocation = lineBlock[lineNumber + 2][0]
                # print( parcelDate + ", " + \
                #         parcelStatut + ", " +
                #         parcelLocation)
                newTrack = Tracking(parcelDate, parcelStatut, parcelLocation)
                cModelTrack.addTracking(newTrack)
            #cModelTrack.printTrack()
            print("Hello, world!")
            return cModelTrack
示例#5
0
def listTracking(bot, update):
    tg_user = update.message.chat_id

    userdb = User.select().where(User.telegramId == tg_user).get()

    activeTrackings = Tracking.select().where(Tracking.user == userdb.id)

    message = 'Tus trackins registrados son estos: \n'
    for item in activeTrackings:
        message = message + str(item.asin) + '\n'

    bot.send_message(chat_id=update.message.chat_id, text=message)
示例#6
0
def cmd_sub(bot, update, args, chat=None):
    if len(args) < 1:
        bot.reply(update, "Use /sub username1 username2 username3 ...")
        return
    tw_usernames = args
    not_found = []
    already_subscribed = []
    successfully_subscribed = []

    for tw_username in tw_usernames:
        tw_user = bot.get_tw_user(tw_username)

        if tw_user is None:
            not_found.append(tw_username)
            continue

        if Tracking.select().where(Tracking.tw_user == tw_user,
                                   Tracking.tg_chat == chat).count() == 1:
            already_subscribed.append(tw_user.full_name)
            continue

        Tracking.create(tg_chat=chat, tw_user=tw_user)
        successfully_subscribed.append(tw_user.full_name)

    reply = ""

    if len(not_found) is not 0:
        reply += "Sorry, I didn't find username{} {}\n\n".format(
            "" if len(not_found) is 1 else "s", ", ".join(not_found))

    if len(already_subscribed) is not 0:
        reply += "You're already subscribed to {}\n\n".format(
            ", ".join(already_subscribed))

    if len(successfully_subscribed) is not 0:
        reply += "I've added your subscription to {}".format(
            ", ".join(successfully_subscribed))

    bot.reply(update, reply)
def testquery(request):
    # creates dummy posts

    p1 = Post(
        url="boobies",
        date="",
        last_track=datetime.datetime.utcnow().replace(tzinfo=utc),
        image="",
        note_count=2,
        note_inc=165,
        text="big",
    )
    p1.save()

    tracking1 = Tracking(
        post=p1, timestamp=datetime.datetime.utcnow().replace(tzinfo=utc), sequence=0, increment=0, count=0
    )
    tracking1.save()
    print(tracking1.post.url)

    # p2=Post(url='ilikecouches', date='', image='', note_count=2, note_inc=33, text='sofa')
    # p2.save()
    # p3=Post(url='foodporn', date='', image='', note_count=2, note_inc=66, text='bbq')
    # p3.save()
    # p4=Post(url='artandstuff', date='', image='', note_count=2, note_inc=0, text='hipster')
    # p4.save()

    # create a blog
    b = Blog(host_name="MOFOBITCH", timestamp=datetime.datetime.utcnow().replace(tzinfo=utc))
    b.save()
    # add the dummy posts to the blog's likes field
    # b.likes.add(p1,p2,p3,p4)
    # query the blog 'MOFOBITCH' and sort all of its likes field by note_inc in descending
    # order, and return a QuerySet of the top 3 note_inc posts
    # b2=Blog.objects.get(host_name='MOFOBITCH').likes.order_by('-note_inc')[0:3]
    # for e in b2:
    # print(e)
    return HttpResponse(200)
示例#8
0
def removeTracking(bot, update):
    tg_user = update.message.chat_id
    userdb = User.select().where(User.telegramId == tg_user).get()
    activeTrackings = Tracking.select().where(Tracking.user == userdb.id)

    button_list = []
    for item in activeTrackings:
        button_list.append(
            InlineKeyboardButton(item.asin, callback_data=item.id))

    reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=1))
    bot.send_message(
        tg_user,
        "Estos son tus trackings activos, selecciona el que desees borrar:",
        reply_markup=reply_markup)
示例#9
0
def showpost(code):
    singlepost = Posts.query.filter_by(post_code=code).first_or_404()
    flash(singlepost.id, "warning")
    user_code = request.args.get('ref')
    remote_addr = request.remote_addr

    db.session.expire_on_commit = False
    singlepost = Posts.query.filter_by(post_code=code).first_or_404()

    if (user_code):
        tup = hashids.decode(user_code)
        try:
            user_code = float(tup[0])
        except:
            user_code = -1

    if (Tracking.query.filter(Tracking.post_ID == singlepost.id).filter(
            Tracking.ip == remote_addr).filter(
                Tracking.user_ID == user_code).scalar() is None):
        newtrack = Tracking(singlepost.id, user_code, remote_addr)
        db.session.add(newtrack)

        if (Points.query.filter(Points.post_ID == singlepost.id).filter(
                Points.user_ID == user_code).scalar() is None):
            newpoint = Points(user_code, singlepost.id, 1)
            db.session.add(newpoint)

        else:
            element = Points.query.filter(
                Points.post_ID == singlepost.id).filter(
                    Points.user_ID == user_code).first()
            element.earned_points += 1
        try:
            db.session.commit()
        except:
            db.session.rollback()
        finally:
            db.session.close()

    return render_template("main/single.html",
                           title="post",
                           singlepost=singlepost)
示例#10
0
 def get_tracking(self, tg_chat):
     db_chat, _created = Tracking.get_or_create(
         chat_id=tg_chat.id,
         tg_type=tg_chat.type,
     )
     return db_chat
示例#11
0
login_page = browser.get('http://183.177.124.6/24online/webpages/myaccountlogin.jsp')

login_form = login_page.soup.select('form')[0]

login_form.select('[name="username"]')[0]['value'] = ''
login_form.select('[name="password"]')[0]['value'] = ''

page2 = browser.submit(login_form, login_page.url)

remaining_data = page2.soup.select('#datausagediv1 > table > tr > td > font')[-1].text

package_expiry = page2.soup.select('td.inputtd > font')
package_expiry_date = datetime.datetime.strptime(package_expiry[5].text, '%d/%m/%Y %H:%M')
remaining_data

add_data = Tracking.create(remaining_data=remaining_data.strip('MBmbKGkg'))
add_data.save()

expires_in = package_expiry_date - datetime.datetime.now()
print "Expires in {} days".format(expires_in.days)
data_in_gb = round(float(remaining_data.strip('GMKBgmkb'))/1024, 2)
print "{}, or {} GB of data remaining".format(remaining_data, data_in_gb)

today = datetime.date.today()

last_30_days = arrow.now().replace(days=-30).naive


query = Tracking.select().where(Tracking.added_time >= last_30_days).order_by(Tracking.added_time.asc())

first_day = list(query)[0]
示例#12
0
def _parse_post_json(blog_host_name, liked_post_json):
    ''' Takes the json from a post and extracts all its juicy goodness, then
        makes a database entry for it, if necessary.'''
    
    # Check the last time this post was tracked and ignore if 
    # it's within the last hour.
    new_post = not Post.objects.filter(post_id = liked_post_json['id']).exists()
    
    if (not new_post):
        this_post = Post.objects.get(post_id = liked_post_json['id'])
        deltatime = datetime.datetime.now().replace(tzinfo=utc) - \
            this_post.last_track.replace(tzinfo=utc)            
        if (deltatime.total_seconds()/pv.tracking_interval < 1):
            return 0 
    
    # TODO: this could return an error if the post in our database belongs to another blog!!!!!
    blog_obj = Blog.objects.get(host_name = blog_host_name)
    
    # Example: liked_post_json['post_url'] to get the url
    post_id = liked_post_json['id']
    post_url = liked_post_json['post_url']
    post_date = convert_date(liked_post_json['date'])
    post_count = liked_post_json['note_count']
    current_datetime = datetime.datetime.now().replace(tzinfo=utc)
    
    # Different posts have different types of text fields.
    text_field = {"text": "body",
                  "chat": "body",
                  "photo": "caption",
                  "link": "description",
                  "quote": "source",
                  "answer": "answer",
                  "audio": "caption",
                  "video": "caption"}
    # Set default image.
    def_img = "http://www.athgo.org/ablog/wp-content/uploads/2013/02/tumblr_logo.png"
                  
    img_field = {"text": lambda: def_img,
                  "chat": lambda: def_img,
                  "photo": lambda:liked_post_json['photos'][0]['alt_sizes'][0]['url'],               
                  "link": lambda: def_img,
                  "quote": lambda: def_img,
                  "answer": lambda: def_img,
                  "audio": lambda: liked_post_json.get('album_art', def_img),
                  "video": lambda: def_img}
    updated_times_tracked = 1              
    img = img_field[liked_post_json['type']]()
    txt = strip_tags(liked_post_json[text_field[liked_post_json['type']]].encode('utf-8'))
    
    # Reduce text length if too long.
    if len(txt) > 100:
        txt = txt[:100] + "..."
    
    if (new_post):
        post_obj = Post(post_id = post_id,
                        url = post_url,
                        date = post_date,
                        last_track = current_datetime,
                        times_tracked = 1,
                        image = img,
                        note_count = post_count,
                        note_inc = 0,
                        text = txt)
        
        post_obj.save()
        blog_obj.likes.add(post_obj)  
        blog_obj.save()
    
    else:
        # update note_count and last_track.
        post_obj = Post.objects.get(post_id=post_id)
        prev_count = post_obj.note_count
        updated_times_tracked = post_obj.times_tracked + 1
        Post.objects.filter(post_id=post_id).update(times_tracked = updated_times_tracked, 
                                                 note_inc = post_count - prev_count,
                                                 note_count = post_count,
                                                 last_track = current_datetime)
    # Create new tracking object for post.
    tracking = Tracking(post = post_obj,
                        timestamp = current_datetime,
                        increment = post_obj.note_inc,
                        sequence = updated_times_tracked,
                        count = post_obj.note_count)
    tracking.save()
    
    return 0