Advertisement
Guest User

Untitled

a guest
Oct 6th, 2017
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.34 KB | None | 0 0
  1. __author__ = "Benjamin Keith (ben@benlk.com)"
  2.  
  3. import sys, os, random, re, time, ConfigParser, string
  4. from twisted.words.protocols import irc
  5. from twisted.internet import protocol
  6. from twisted.internet import reactor
  7. from collections import defaultdict
  8. from time import localtime, strftime
  9.  
  10. #
  11. # Setting some settings
  12. #
  13.  
  14. config_file = sys.argv[1]
  15.  
  16. requiredconfig = [('Connection', 'host'), ('Connection', 'port'), ('Bot', 'nickname'), ('Bot', 'erroneousNickFallback'), ('Bot', 'Channel'), ('Bot', 'realname'), ('Bot', 'username'), ('Bot', 'userinfo'), ('Brain', 'reply'), ('Brain', 'brain_file'), ('Brain', 'ignore_file'), ('Brain', 'STOP_WORD'), ('Brain', 'chain_length'), ('Brain', 'chattiness'), ('Brain', 'max_words')];
  17. config = ConfigParser.ConfigParser()
  18. config.read(config_file)
  19. for setting in requiredconfig:
  20. if not config.has_option(setting[0], setting[1]):
  21. sys.exit('Error: Option "' + setting[1] + '" in section "' + setting[0] + '" is required! Take a look at your config.ini')
  22.  
  23. host = config.get('Connection', 'host')
  24. port = int(config.get('Connection', 'port'))
  25. password = config.get('Connection', 'password')
  26.  
  27. nickname = config.get('Bot', 'nickname')
  28. erroneousNickFallback = config.get('Bot', 'erroneousNickFallback')
  29. channel = config.get('Bot', 'channel')
  30. chan = channel
  31. realname = config.get('Bot', 'realname')
  32. username = config.get('Bot', 'username')
  33. userinfo = config.get('Bot', 'userinfo')
  34. versionName = "sadface bot rev. 10"
  35.  
  36. reply = config.get('Brain', 'reply')
  37. markov = defaultdict(list)
  38. brain_file = config.get('Brain', 'brain_file')
  39. STOP_WORD = config.get('Brain', 'STOP_WORD')
  40. # punctuation = ['\n', '.', '?', '!', ',', '\r']
  41. # Chain_length is the length of the message that sadface compares
  42. chain_length = int(config.get('Brain', 'chain_length'))
  43. chattiness = float(config.get('Brain', 'chattiness'))
  44. max_words = int(config.get('Brain', 'max_words'))
  45. ignore_file = config.get('Brain', 'ignore_file')
  46. ignore_nicks = []
  47. for line in open(ignore_file, 'r'):
  48. ignore_nicks.append(line.strip())
  49. #
  50. # Begin actual code
  51. #
  52.  
  53. def add_to_brain(msg, chain_length, write_to_file=False):
  54. if write_to_file:
  55. f = open(brain_file, 'a')
  56. f.write(msg + '\n')
  57. f.close()
  58. buf = [STOP_WORD] * chain_length
  59. for word in msg.split():
  60. markov[tuple(buf)].append(word)
  61. del buf[0]
  62. buf.append(word)
  63. markov[tuple(buf)].append(STOP_WORD)
  64.  
  65. # TODO
  66. # Find the brain state, keep it saved on disk instead of in RAM.
  67.  
  68. def generate_sentence(msg, chain_length, max_words=1000): #max_words is defined elsewhere
  69. if msg[-1][-1] in string.punctuation:
  70. # msg[-1] = msg[-1][:-1]
  71. # msg.replace([-1], '')
  72. # converts string to list, drops the end character, converts back to string
  73. msg = list(msg)
  74. msg[-1] = msg[-1][:-1]
  75. msg[0] = msg[0].upper()
  76. msg = "".join(msg)
  77. # buf = msg.split()[-chain_length:]
  78. buf = msg.split()[:chain_length]
  79.  
  80. # If message is longer than chain_length, shorten the message.
  81. if len(msg.split()) > chain_length:
  82. message = buf[:]
  83. else:
  84. message = []
  85. for i in xrange(chain_length):
  86. message.append(random.choice(markov[random.choice(markov.keys())]))
  87. for i in xrange(max_words):
  88. try:
  89. next_word = random.choice(markov[tuple(buf)])
  90. except IndexError:
  91. continue
  92. if next_word == STOP_WORD:
  93. break
  94. message.append(next_word)
  95. del buf[0] # What happpens if this is moved down a line?
  96. buf.append(next_word)
  97. return ' '.join(message)
  98.  
  99. def ignore(user):
  100. if user in ignore_nicks:
  101. return True
  102. return False
  103.  
  104. class sadfaceBot(irc.IRCClient):
  105. realname = Benny
  106. username = Benny
  107. userinfo = userinfo
  108. versionName = versionalphalpha
  109. erroneousNickFallback = erroneousNickFallback
  110. password = Thelastwish1
  111.  
  112. def _get_nickname(self):
  113. return self.factory.nickname
  114. nickname = property(_get_nickname)
  115.  
  116. def signedOn(self):
  117. self.join(self.factory.channel)
  118. print "signed on as %s." % (self.nickname,)
  119.  
  120. def joined(self, channel):
  121. print "Joined %s." % (channel,)
  122. self.msg(self.factory.channel, "w")
  123.  
  124. def privmsg(self, user, channel, msg):
  125. # TODO
  126. # make the privmsg class run:
  127. # check for user
  128. # check for reply
  129. # check for self.
  130.  
  131. user_nick = user.split('!', 1)[0]
  132. # Prints the message to stdout
  133. print channel + " <" + user_nick + "> " + msg
  134. if not user:
  135. print "NON-USER:" + msg
  136. return
  137. # Ignores the message if the person is in the ignore list
  138. elif ignore(user_nick):
  139. print "\t" + "Ignored message from <" + user_nick + "> at: " + strftime("%a, %d %b %Y %H:%M:%S %Z", localtime())
  140. # Time method from http://stackoverflow.com/a/415527
  141. # Replies to messages containing the bot's name
  142. elif reply == '1':
  143. if self.nickname in msg:
  144. time.sleep(0.2) #to prevent flooding
  145. msg = re.compile(self.nickname + "[:,]* ?", re.I).sub('', msg)
  146. prefix = "%s: " % (user_nick, )
  147. elif msg.lower().translate(string.maketrans("",""), string.punctuation).startswith(("hello", "hi", "heyo", "salutation", "ayy", "greeting", "what's up")):
  148. time.sleep(0.2) #to prevent flooding
  149. msg = re.compile(self.nickname + "[:,]* ?", re.I).sub('', msg) + " to you"
  150. prefix = "%s: " % (user_nick, )
  151. else:
  152. prefix = ''
  153.  
  154. add_to_brain(msg, self.factory.chain_length, write_to_file=True)
  155. print "\t" + msg #prints to stdout what sadface added to brain
  156. if prefix or random.random() <= self.factory.chattiness:
  157. sentence = generate_sentence(msg, self.factory.chain_length,
  158. self.factory.max_words)
  159. if sentence:
  160. self.msg(self.factory.channel, prefix + sentence)
  161. print ">" + "\t" + sentence #prints to stdout what sadface said
  162. # Replies to messages starting with the bot's name.
  163. elif reply == '2':
  164. if msg.startswith(self.nickname): #matches nickname, mecause of Noxz
  165. time.sleep(0.2) #to prevent flooding
  166. msg = re.compile(self.nickname + "[:,]* ?", re.I).sub('', msg)
  167. prefix = "%s: " % (user_nick, )
  168. else:
  169. msg = re.compile(self.nickname + "[:,]* ?", re.I).sub('', msg)
  170. prefix = ''
  171.  
  172. add_to_brain(msg, self.factory.chain_length, write_to_file=True)
  173. print "\t" + msg #prints to stdout what sadface added to brain
  174. if prefix or random.random() <= self.factory.chattiness:
  175. sentence = generate_sentence(msg, self.factory.chain_length,
  176. self.factory.max_words)
  177. if sentence:
  178. self.msg(self.factory.channel, prefix + sentence)
  179. print ">" + "\t" + sentence #prints to stdout what sadface said
  180.  
  181.  
  182. else: #for when you don't want it talking back
  183. print msg
  184. prefix = ''
  185.  
  186. add_to_brain(msg, self.factory.chain_length, write_to_file=True)
  187. if prefix or random.random() <= self.factory.chattiness:
  188. # sentence = generate_sentence(msg, self.factory.chain_length,
  189. # self.factory.max_words)
  190. pass
  191. #
  192. # Idea for later implementation
  193. # To limit who gets to talk to the bot, the talker's nickname is self.nickname
  194. # if user in allowed_people:
  195. # Check that user is okayed with nickserv
  196. # pass
  197. # else:
  198. # fail
  199. #
  200.  
  201. class sadfaceBotFactory(protocol.ClientFactory):
  202. protocol = sadfaceBot
  203.  
  204. def __init__(self, channel, nickname, chain_length, chattiness, max_words):
  205. self.channel = #OrderoftheTilde
  206. self.nickname = Benny
  207. self.chain_length = chain_length
  208. self.chattiness = chattiness
  209. self.max_words = 500
  210.  
  211. def clientConnectionLost(self, connector, reason):
  212. print "Lost connection (%s), reconnecting." % (reason,)
  213. connector.connect()
  214.  
  215. def clientConnectionFailed(self, connector, reason):
  216. print "Could not connect: %s" % (reason,)
  217. quit()
  218. #
  219. # We begin!
  220. #
  221.  
  222. if __name__ == "__main__":
  223. config_file = sys.argv[1]
  224. if config_file == False:
  225. print "Please specify a valid config file in the arguments."
  226. print "Example:"
  227. print "python sadface_configgable.py default.ini"
  228. if os.path.exists(brain_file):
  229. f = open(brain_file, 'r')
  230. for line in f:
  231. add_to_brain(line, chain_length)
  232. print 'Brain reloaded'
  233. f.close()
  234. else:
  235. print "Hoi! I need me some brains! Whaddya think I am, the Tin Man?"
  236. reactor.connectTCP(host, port, sadfaceBotFactory('#' + channel, nickname, chain_length, chattiness, max_words))
  237. reactor.run()
  238.  
  239. <?php
  240.  
  241. // Our bot's configuration parameters
  242. $server = 'irc.orderofthetilde.net' ;
  243. $port = 6697;
  244. $nickname = 'Benny';
  245. $ident = 'Benny';
  246. $gecos = 'Benny v1.0';
  247. $channel = '#OrderoftheTilde';
  248.  
  249. // Connect to network
  250.  
  251. $socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
  252. $error = socket_connect( $socket, $server, $port );
  253.  
  254. // Add some error handling in case connection was not successful
  255. if ( $socket === false ) {
  256. $errorCode = socket_last_error();
  257. $errorString = socket_strerror( $errorCode );
  258. die( "Error $errorCode: $errorString\n" );
  259. }
  260.  
  261. // Send the registration info
  262. socket_write( $socket, "NIACK $nickname\r\n" );
  263. socket_write( $socket, "USER $ident * 8 :$gecos\r\n" );
  264.  
  265. // Finally, loop until the socket closes
  266.  
  267. while ( is_resource( $socket ) ) {
  268.  
  269. // Fetch data from socket
  270. $data = trim( socket_read( $socket, 1024, PHP_NORMAL_READ ) );
  271. echo $data . "\n";
  272.  
  273. // Splitting data into chunks
  274. $d = explode(' ', $data);
  275.  
  276. // Padding array avoids ugly undefined offset errors
  277. $d = array_pad( $d, 10, '' );
  278.  
  279. }
  280.  
  281. if ( $d[1] === '376' || $d[1] === '422' ) {
  282. socket_write( $socket, 'JOIN' . $channel . "\r\n" );
  283. }
  284.  
  285. // [0] [1] [2] [3]
  286. // :Nickname!ident@hostname PRIVMSG #OrderoftheTilde :!paranoid
  287. if ( $d[3] == ':!paranoid' ) {
  288. $paranoid = "P" . str_repeat( "o", mt_rand(2, 15) );
  289. }
  290. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement