コード例 #1
0
ファイル: botimpl.py プロジェクト: lifthrasiir/himawari
def call(channel, source, msg):
    if u'꺼져' in msg or u'나가' in msg:
        r = get_renderer(channel, None)
        reply = r.render(KEYNAME_DYINGMSG, default=u'사쿠라코는 오늘 점심 없어요.')
        bot.send('PART %s :%s' % (channel, reply.encode('utf-8')))
    else:
        say(channel, u'%s 뻘글 생산봇입니다. 자세한 사용법은 http://himawari.mearie.org/ 를 참고하세요.' %
                attach_postposition(bot.NICK.decode('utf-8'), u'는'))
コード例 #2
0
def sendif(t, ms_params):
    global recv_prev

    if recv_prev:
        return

    if t == None:
        recv_prev = True
    else:
        for i in t.split('|'):
            if eq(i, recv_msg.text):
                recv_prev = True
                break

    if recv_prev == True:
        for i in ms_params:
            send(recv_user, Message(*i))
コード例 #3
0
async def run():
    res = client.get(url)
    print(res)
    soup = BeautifulSoup(res.text, 'lxml')
    sub_class=soup.find(id='availability')  #finding that particular div 
    print('amazon.com -> ')
    if sub_class:   #above result can be none so checking if result is not none
        text = sub_class.find("span", {"class": "a-size-medium"}).text.strip()
        print("availability : {}".format(text)) 
        msg = ""
        stock = False
        if (text == 'In Stock.'):
            msg = "HOSTIAAAAA 😲 Que la PS5 esta en stock! 🔥\n%s\nMensaje: %s" % (url, text)
            stock = True
        elif (text == 'Only 1 left in stock - order soon.'):
            msg = "CORREEEEE 😲 Que solo queda UNA PS5 en stock! 🔥\n%s\nMensaje: %s" % (url, text)
            stock = True
        else:
            msg = "F... La PS5 no esta en stock 😢\n%s\nMensaje: %s" % (url, text)
            stock = True
        if (stock): bot.send(msg)
コード例 #4
0
ファイル: utils.py プロジェクト: ARiDa/graphast-examples
def generateTimes(n_tests=10,from_file="../tests.txt",operations=operations,save_file="../test_results.csv"):
    resetFile(filename=save_file)

    start = time()
    #files = [open("../{}Results.csv".format(file_name)) for file_name in operations]
    result_file = open(save_file,'a')
    with open(from_file) as tests_file:
        result_file.write(','.join(operations))
        result_file.write(",Distance(m)")
        result_file.write('\n')
        
        for line in tests_file:
            positions = line.split(",")
            positions[3] = positions[3]
            #print(positions)

            results = []
            for op in operations:
                cmd = 'cd ../ && mvn exec:java -Dexec.mainClass="org.graphast.example.{}Example" -Dexec.args="{} {} {} {} {}Output.txt" > /dev/null'.format(op, \
                    positions[0], positions[1], positions[2], positions[3], op)
                sum_times = 0
                #obtendo média dos testes
                for _ in range(n_tests):
                    os.system(cmd)
                    with open("../{}Output.txt".format(op)) as f:
                        sum_times += int(f.readline()[0:-1])
                
                results.append(str(sum_times/n_tests))  

            with open("../{}Output.txt".format(operations[0])) as f:
                f.readline()
                results.append(f.readline()[0:-1])

            print(results)
            result_file.write("{}\n".format(','.join(results)))
    end = time()
    result_file.close()
    bot.send("Tempos gerados em {}".format(str(dt.timedelta(seconds=(end-start)))))
コード例 #5
0
if len(sys.argv) == 1:
    latest = 0
else:
    latest = int(sys.argv[1])

f = open("./site_link", 'r')
URL = f.readline()
f.close()

response = requests.get(URL)
# print("CODE : ",response.status_code)

if response.status_code != 200:
    err = "서버 에러인지 확인하자 : %d" % response.status_code
    # print(err)
    bot.send(err)
    # exec("python /send.py '%s'" % err)
    import sys
    sys.exit()

# print(response.text)
# tableFrom = response.text.find("class=\"bd_lst bd_tb_lst bd_tb\"")
# tableTo = response.text.find("<div class=\"btm_mn clear\">")

# 정규식으로 검색
from bs4 import BeautifulSoup
html = BeautifulSoup(response.text, 'html.parser')

lists = html.find('table', {'class': 'bd_lst bd_tb_lst bd_tb'}).find('tbody')

# print(lists)
コード例 #6
0
 def notify(self, msg):
     bot.send(msg)
コード例 #7
0
import requests, time

print("main: {}".format(__name__))
if __name__ == "__main__":
    print("start0")
    db = SQLighter()
    while True:
        print('New check')
        if True:
            users = db.live_update_list()
            print("Get {} users".format(len(users)))
            if users:
                for u in users:
                    cor = core(idd=u['id'])
                    command, messid, *_ = u['live_update_mode'].split(';')
                    if command == 'sport':
                        commandall = '/{} -20'.format(command)
                    else:
                        commandall = '/{}'.format(command)
                    data = cor.command(commandall, live_update=True)
                    data['messId'] = messid
                    data['command'] = command
                    data['live_update'] = True
                    print(data)
                    sent_info = bot.send(data=data, to=u['telid'])
                    cor.close(data=data, sent_info=sent_info, mode='command')

        # except Exception as e:
        #     print("{!s}\n{!s}".format(type(e), str(e)))
        # time.sleep(20)
        time.sleep(600)
コード例 #8
0
ファイル: main.py プロジェクト: Melnikovartem/MVP
import database as db
import bot
from time import sleep, strftime
import config
while True:
    try:
        db.push()
        for post in db.pull():
            bot.send(post)
        print("Done", strftime("%c"))
    except Exception as e:
        print("!Error", e)
    sleep(config.time_sleep)

コード例 #9
0
ファイル: botimpl.py プロジェクト: lifthrasiir/himawari
def start():
    c = DB.execute('select channel from channels where active=1;', ())
    for channel, in c.fetchall():
        channel = channel.encode('utf-8')
        bot.send('JOIN %s' % channel)
        welcome(channel, None) # 누구한테도 초대받은 게 아니니까...
コード例 #10
0
def main():
    frame = None
    print('Starting security camera')
    visitedCount = 0
    lastTimeVisitedCountCleared = datetime.now()
    visitorFirstArrived = None
    visitorMostRecentlySeen = None
    lastTimeBackgroundReset = datetime.now()
    savingVisitorImage = datetime.now()
    frames = []
    savingVideoFrames = False
    savingVideo = False

    vs = cv2.VideoCapture(secrets.LINK_WITH_PASSWORD)
    if vs is None or not vs.isOpened():
        print('Unable to open security camera', vs)
        exit()

    backGround = None
    emailedAboutVisitor = False

    while (True):

        if visitedCount > 0 and (datetime.now() - lastTimeVisitedCountCleared
                                 ).seconds > SECONDS_TO_CLEAR_COUNTER:
            print("Lost visitor, resetting counter...")
            lastTimeVisitedCountCleared = datetime.now()
            visitedCount = 0
            visitorFirstArrived = None
            visitorMostRecentlySeen = None
            emailedAboutVisitor = False
            if savingVideo:
                now = datetime.now()
                folder = str(now.month) + '-' + str(now.day) + '-' + str(
                    now.year)
                saveVideo(folder + '/' + str(datetime.now()), frames)
                savingVideo = False
            savingVideoFrames = False
            frames = []

        text = "No one's here :("
        ret, frame = vs.read()
        frame = cv2.resize(frame, None, fx=.4, fy=.4)
        frame = frame[TOP_CROP:len(frame), 0:len(frame[0])]
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (21, 21), 0)

        if backGround is None or (datetime.now() - lastTimeBackgroundReset
                                  ).seconds >= SECONDS_TO_RESET_BACKGROUND:
            backGround = gray
            lastTimeBackgroundReset = datetime.now()
            continue

        frameDelta = cv2.absdiff(backGround, gray)
        thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
        thresh = cv2.dilate(thresh, None, iterations=2)
        cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)

        height, width, _ = frame.shape

        foundVisitor = False
        for c in cnts:
            # if the contour is too small, ignore it
            if cv2.contourArea(c) < MIN_AREA:
                continue

            foundVisitor = True

            # compute the bounding box for the contour, draw it on the frame,
            # and update the text
            (x, y, w, h) = cv2.boundingRect(c)
            #cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)
            text = "There's a Visitor! :)"

        cv2.putText(frame, "Room Status: {}".format(text), (10, 20),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

        if foundVisitor:
            savingVideoFrames = True
            lastTimeVisitedCountCleared = datetime.now()
            visitedCount += 1
            if visitorFirstArrived == None:
                print("Visitor first arrived now")
                visitorFirstArrived = datetime.now()
            else:
                visitorMostRecentlySeen = datetime.now()

            if SAVING_VISITOR_IMAGES and (datetime.now(
            ) - savingVisitorImage).seconds >= SECONDS_TO_SAVE_VISITOR_IMAGES:
                now = datetime.now()
                savingVisitorImage = now
                folder = str(now.month) + '-' + str(now.day) + '-' + str(
                    now.year)
                if not os.path.isdir(folder):
                    os.mkdir(folder)
                fileName = str(now)
                mostRecentFile = folder + '/' + fileName + '.jpg'
                cv2.imwrite(mostRecentFile, frame)

        if EMAIL_ENABLED and visitorFirstArrived != None and visitorMostRecentlySeen != None:
            diff = (visitorMostRecentlySeen - visitorFirstArrived).seconds
            if diff >= SECONDS_TO_EMAIL_AFTER_ARRIVAL and (
                    not emailedAboutVisitor):
                emailedAboutVisitor = True
                print("Notifying now")

                msg = 'There\'s an animal at the door!\n'

                if bot.ready:
                    bot.send("There\'s an animal at the door!")
                    bot.sendFile(getMostRecentImage())

                savingVideo = True

        if DISPLAY:
            cv2.imshow("Security Feed", frame)
            #cv2.imshow("Background", backGround)
            #cv2.imshow("Thresh", thresh)
            #cv2.imshow("Frame Delta", frameDelta)

            #cv2.imshow('frame',gray)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        if savingVideoFrames:
            frames.append(frame)

    vs.release()
    cv2.destroyAllWindows()
    exit()