我编写了这个脚本,以便在修改文件 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"])