· 6 years ago · Jan 26, 2019, 04:18 AM
1from twitter import *
2import random
3import time
4import pickle
5import time
6import json
7
8def tweetGen(tedMap,n = 254):
9 """
10 Takes a dictionary storing
11 a Markov model and
12 posts 15 tweets to Twitter
13 """
14
15 # For updating the prefix
16 def shift(t, word):
17 """
18 Inputs
19 t: tuple of strings
20 word: string
21 Output: tuple of strings
22 """
23 return t[1:] + (word,)
24
25 # Just the text
26 def randomTed(suffixMap, n = 254):
27 """
28 Inputs
29 suffixMap: a dictionary
30 n: an int, # characters to be output
31
32 Output
33 status: a string to be tweeted
34 """
35 # choose a random starting point
36 pref = random.choice(list(suffixMap.keys()))
37 # initialize output string
38 status = ' '.join(pref)
39 # till our status is long enough
40 while len(status) < n:
41 suffixList = suffixMap.get(pref)
42 if suffixList == None:
43 status = status + randomTed(suffixMap, n - len(status))
44 # sample from current suffixes
45 word = random.choice(suffixList)
46 # update status, appending word
47 status = status + ' ' + word
48 # update current prefix
49 pref = shift(pref, word)
50 return status
51
52 # For communicating with Twitter
53 CONSUMER_KEY = 'XXX'
54 CONSUMER_SECRET = 'XXX'
55 OAUTH_TOKEN = 'XXX'
56 OAUTH_TOKEN_SECRET = 'XXX'
57
58 # Then, we store the OAuth object in "auth"
59 auth = OAuth(OAUTH_TOKEN,OAUTH_TOKEN_SECRET,CONSUMER_KEY,CONSUMER_SECRET)
60 # Connection object
61 t = Twitter(auth=auth)
62
63 # Getting tweets from our list
64 slug = "just-surrogate-things"
65 owner = "MaxTedroom"
66 bigList = t.lists.statuses(owner_screen_name=owner, slug=slug, count=1000)
67
68 tags = []
69 for twt in bigList:
70 tags.extend(twt['entities']['hashtags'])
71 tags = [x['text'] for x in tags]
72
73 # Create a list of tweets
74 tagsList = [random.choice(tags) for _ in range(15)]
75 tweetList = [ randomTed(tedMap, n - len(tag)) + ' #' + tag for tag in tagsList]
76
77 # Finally, do the tweeting
78 for tweet in tweetList:
79 t.statuses.update(status = tweet)
80 err = random.choice([3,4,5])
81 time.sleep(20+err)
82
83 # Explicit return of None, just for me
84 return None