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
):
61 cmd
= list[4].split(" ")[0]
64 fp
= list[4].split(" ")[1]
69 statetab
= pickle
.load(pkfile
)
72 print "Could not load db: Doesn't exist\n"
75 #pickles out the state to a file
76 def markov_dump(c
,list,bot
):
82 cmd
= list[4].split(" ")[0]
85 fp
= list[4].split(" ")[1]
87 pkfile
= open(fp
,"w+")
89 pickle
.dump(statetab
,pkfile
)
93 def markov_learn(c
,list,bot
):
94 """ Should not be called directly """
97 cmd
= list[4].split(" ")[0]
98 if cmd
== "talk" or cmd
== "markov_stats" or cmd
== "mkload" or cmd
== "mkdump":
102 words
= [x
.lower().strip() for x
in list[4].split(" ") if not x
.isspace()]
110 #go through every word and put them in a hash table.
111 #EX the sentence "Mary had a little lamb"
112 #first iteration, w1 and w2 are both empty.
113 #statetab[w1][w2] doesn't exist, so make it and set
114 #statetab[""][""] to Mary.
116 #Then, set w1 to w2 and w2 to i, so the chain moves forward.
118 statetab
.setdefault((w1
,w2
),[]).append(i
)
121 statetab
.setdefault((w1
,w2
),[]).append("\n")
123 if nickmatch
.search(list[4]) and bot
.autorep
== 1 and random
.randint(0,10) == 0:
124 tmp
= emit_chain(random
.choice(list[4].split(" ")))
129 c
.privmsg(list[5], "%s: %s" % (list[0],tmp
))
133 if random
.randint(0,15) == 0 and bot
.talk
== 1:
134 c
.privmsg(list[5], "%s" % (emit_chain(random
.choice(list[4].split(" ")))))
149 #make the first word the key if its not a space
160 newword
= random
.choice(statetab
[(w1
,w2
)]).strip()
164 retval
= retval
+ newword
+ " "
169 #max of rand words if we don't hit a space or other error
170 if i
>= random
.randint(5,50):
175 def markov_talk(c
,list,bot
):
176 """ Makes the markov chain talk to you """
179 cmd
= list[4].split(" ")[0]
182 key
= list[4].split(" ")[1].lower()
186 if list[3] and cmd
== "talk":
187 tmp
= emit_chain(key
);
191 c
.privmsg(list[5],"%s %s" % (key
, tmp
))
195 def tweet(c
, args
, bot
):
196 cmd
= args
[4].split(" ")[0]
200 c
.privmsg(args
[5], "Updated Twitter with message: %s" % last
)