1 #markov module for scrappy
3 #the inspiration for this code comes from
4 #"The Practice of Programming", so some of the variable
5 #names and such will be similar.
18 twitteruser
= 'scrappybot'
19 twitterpass
= 'mark0vb0t'
32 lock
= threading
.Lock()
34 scrap
.register_event("markov", "msg", markov_learn
)
35 scrap
.register_event("markov", "msg", markov_talk
)
36 scrap
.register_event("markov", "msg", markov_load
)
37 scrap
.register_event("markov", "msg", markov_dump
)
38 scrap
.register_event("markov", "msg", markov_stats
)
39 scrap
.register_event("markov", "msg", tweet
)
41 nickmatch
= re
.compile(scrap
.nickname
)
45 api
= twitter
.Api(username
=twitteruser
, password
=twitterpass
)
47 def markov_stats(c
,list,bot
):
50 cmd
= list[4].split(" ")[0]
52 if cmd
== "markov_stats":
53 c
.privmsg(list[5], "words: %d" % len(statetab
[("\n","\n")]))
54 c
.privmsg(list[5], "chains: %d" % len(statetab
.items()))
56 #loads in a previously pickled saved state
57 def markov_load(c
,list,bot
):
60 cmd
= list[4].split(" ")[0]
63 fp
= list[4].split(" ")[1]
67 statetab
= pickle
.load(pkfile
)
69 print "Could not load db: Doesn't exist\n"
72 #pickles out the state to a file
73 def markov_dump(c
,list,bot
):
79 cmd
= list[4].split(" ")[0]
82 fp
= list[4].split(" ")[1]
84 pkfile
= open(fp
,"w+")
86 pickle
.dump(statetab
,pkfile
)
90 def markov_learn(c
,list,bot
):
91 """ Should not be called directly """
96 words
= [x
for x
in list[4].split(" ") if not x
.isspace()]
104 #go through every word and put them in a hash table.
105 #EX the sentence "Mary had a little lamb"
106 #first iteration, w1 and w2 are both empty.
107 #statetab[w1][w2] doesn't exist, so make it and set
108 #statetab[""][""] to Mary.
110 #Then, set w1 to w2 and w2 to i, so the chain moves forward.
112 statetab
.setdefault((w1
,w2
),[]).append(i
)
115 statetab
.setdefault((w1
,w2
),[]).append("\n")
117 if nickmatch
.search(list[4]) and bot
.autorep
== 1 and random
.randint(0,10) == 0:
118 tmp
= emit_chain(random
.choice(list[4].split(" ")))
123 c
.privmsg(list[5], "%s: %s" % (list[0],tmp
))
127 if random
.randint(0,15) == 0 and bot
.talk
== 1:
128 c
.privmsg(list[5], "%s" % (emit_chain(random
.choice(list[4].split(" ")))))
143 #make the first word the key if its not a space
154 newword
= random
.choice(statetab
[(w1
,w2
)])
158 retval
= retval
+ newword
+ " "
163 #max of rand words if we don't hit a space or other error
164 if i
>= random
.randint(5,50):
169 def markov_talk(c
,list,bot
):
170 """ Makes the markov chain talk to you """
173 cmd
= list[4].split(" ")[0]
176 key
= list[4].split(" ")[1]
180 if list[3] and cmd
== "talk":
181 tmp
= emit_chain(key
);
185 c
.privmsg(list[5],"%s" % tmp
)
189 def tweet(c
, args
, bot
):
190 cmd
= args
[4].split(" ")[0]
194 c
.privmsg(args
[5], "Updated Twitter with message: %s" % last
)