0

我编写了这个脚本,以便在修改文件 results.txt 时向自己发送短信。它将文件内容以文本形式发送到我的手机(我已经更改了问题中的数字)。它有效,除了每次修改我都会收到两条相同的 SMS 消息,而且我一生都无法弄清楚原因。

import time
import sys, os
from twilio.rest import Client
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler


class MyHandler(PatternMatchingEventHandler):
        patterns = ["./results.txt"]

        def process(self, event):
                with open('results.txt', 'r') as myfile:
                        newtweet=myfile.read().replace('\n', '')
                        client = Client("ACac14lkjdchlkdhfdhb448d175335fbd8", "hduhdhdhddhidh39837382783232")
                        client.messages.create(from_="+44145698039",
                        to="+44778974188",
                        body=newtweet)


        def on_modified(self, event):
                self.process(event)



if __name__ == '__main__':
    args = sys.argv[1:]
    observer = Observer()
    observer.schedule(MyHandler(), path=args[0] if args else '.')
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

编辑**

这是写入 results.txt 的文件:

class MyStreamListener(tweepy.StreamListener):

        def on_status(self, status):
                text = status.text
                name = status.user.screen_name
                uid = status.user.id
                print (text)
                print (uid, text, name, file=open("results.txt", "w"))

        def on_error(self, status_code):
                if status_code == 420:
                        return False

myStreamListener = MyStreamListener()
users = ['22776208', '2845678578']
stream = tweepy.Stream(auth = api.auth, listener=myStreamListener, include_entities=True)
stream.filter(follow=users, languages=["en"])
keywords = ["Trump"]
stream.filter(track=keywords, languages=["en"])
4

1 回答 1

0

Twilio 开发人员布道者在这里。

我相信,通过阅读这个问题,当你打电话时,file.open你会导致一个修改的事件,然后当你写入文件时,你也会导致事件触发。因此,您发送了两条消息,因为 change 事件被触发了两次。

与其每次要写入文件时都打开文件,不如保存对准备写入的文件的引用并每次都写入相同的引用。

就像是:

class MyStreamListener(tweepy.StreamListener):

    def __init__(self, file):
            self.file = file
            super().__init__()

    def on_status(self, status):
            text = status.text
            name = status.user.screen_name
            uid = status.user.id
            print (text)
            print (uid, text, name, self.file)

    def on_error(self, status_code):
            if status_code == 420:
                    return False

myStreamListener = MyStreamListener(file=open("results.txt", "w"))

(如果这不能完全正常工作,请原谅,我的 Python 不是一流的,但希望您能明白这一点,将打开的文件对象传递给您的侦听器并使用它,而不是每次都打开文件。)

于 2017-07-18T14:55:21.227 回答