-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
89 lines (70 loc) · 2.71 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from twython import TwythonStreamer
from pymongo import MongoClient
import os
import slack
from vocabulary import BANS, TECHS, RH
# client = MongoClient()
# db = client.freeleads
# tweets = db.tweet
# leads = db.lead
SLACK_API_TOKEN = os.environ.get('SLACK_API_TOKEN')
TWITTER_APP_KEY = os.environ.get('TWITTER_APP_KEY')
TWITTER_APP_SECRET = os.environ.get('TWITTER_APP_SECRET')
TWITTER_OAUTH_TOKEN = os.environ.get('TWITTER_OAUTH_TOKEN')
TWITTER_OAUTH_TOKEN_SECRET = os.environ.get('TWITTER_OAUTH_TOKEN_SECRET')
class LeadStreamer(TwythonStreamer):
def on_success(self, data):
if data.get("retweeted_status"): # filter retweets
print("RETWEET")
return
self.detect_lead(data)
def on_error(self, status_code, data, headers=None):
print(status_code)
print(data)
self.disconnect()
def detect_lead(self, data):
text, hashtags = self.get_text(data)
url = self.get_url(data)
text_lowered = text.lower()
for ban in BANS:
if ban in text_lowered or ban in hashtags:
return
for tech in TECHS:
if tech in text_lowered or tech in hashtags:
#tweet_id = tweets.insert_one(data).inserted_id
print("TECH")
for rhword in RH:
if rhword in text_lowered or rhword in hashtags:
#lead_id = leads.insert_one(data).inserted_id
print("LEAD")
self.post(url)
break
break
def post(self, url):
slackclient.chat_postMessage(
as_user=False,
username="Twitter bot",
channel='#tuyaux-boulot-twitter-bot',
text=url
)
def get_text(self, data):
text = data.get("extended_tweet", {}).get("full_text") or data.get("text")
print(text)
hashtags = data.get("entities", {}).get("hashtags", [])
hashtags = [h["text"].lower() for h in hashtags]
print(hashtags)
return text, hashtags
def get_url(self, data):
tweet_id = data.get("id")
user = data.get("user")
user_name = user and user.get("screen_name")
if user_name and tweet_id:
url = f"https://twitter.com/{user_name}/status/{tweet_id}"
elif data.get("entities", {}).get("urls"):
url = data.get("entities", {})["urls"][0].get("url")
else:
url = ''
return url
slackclient = slack.WebClient(token=SLACK_API_TOKEN, ssl=False)
stream = LeadStreamer(TWITTER_APP_KEY, TWITTER_APP_SECRET, TWITTER_OAUTH_TOKEN, TWITTER_OAUTH_TOKEN_SECRET)
stream.statuses.filter(track=TECHS, language="fr")