Advertisement
WrenP-Complete

markovbot.py

Oct 5th, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.98 KB | None | 0 0
  1.                     self._tweetingjitter)
  2.                 interval = self._tweetinginterval + jitter
  3.                
  4.                 # Sleep for the interval (in seconds, hence * 60)
  5.                 self._message(u'_autotweet', \
  6.                     u'Next tweet in %d minutes.' % (interval))
  7.                 time.sleep(interval*60)
  8.  
  9.  
  10.     def _check_file(self, filename, allowedext=None):
  11.        
  12.         """Checks whether a file exists, and has a certain extension.
  13.        
  14.         Arguments
  15.        
  16.         filename        -   String that indicates the path to a .txt file
  17.                         that should be read by the bot.
  18.        
  19.         Keyword Arguments
  20.        
  21.         allowedext  -   List of allowed extensions, or None to allow all
  22.                         extensions. Default value is None.
  23.        
  24.         Returns
  25.        
  26.         ok          -   Boolean that indicates whether the file exists,
  27.                         andhas an allowed extension (True), or does not
  28.                         (False)
  29.         """
  30.        
  31.         # Check whether the file exists
  32.         ok = os.path.isfile(filename)
  33.        
  34.         # Check whether the extension is allowed
  35.         if allowedext != None:
  36.             name, ext = os.path.splitext(filename)
  37.             if ext not in allowedext:
  38.                 ok = False
  39.        
  40.         return ok
  41.    
  42.    
  43.     def _construct_tweet(self, database=u'default', seedword=None, \
  44.         prefix=None, suffix=None):
  45.        
  46.         """Constructs a text for a tweet, based on the current Markov chain.
  47.         The text will be of a length of 140 characters or less, and will
  48.         contain a maximum of 20 words (excluding the prefix and suffix)
  49.        
  50.         Keyword Arguments
  51.        
  52.         seedword        -   A string that indicates what word should be in
  53.                         the sentence. If None is passed, or if the word
  54.                         is not in the database, a random word will be
  55.                         chosen. This value can also be a list of words,
  56.                         in which case the list will be processed
  57.                         one-by-one until a word is found that is in the
  58.                         database. Default value is None.
  59.        
  60.         database        -   A string that indicates the name of the
  61.                         specific database that you want to use to
  62.                         generate the text, or u'default' to use the
  63.                         default database. (default = 'default')
  64.  
  65.         prefix      -   A string that will be added at the start of each
  66.                         tweet (no ending space required). Pass None if
  67.                         you don't want a prefix. Default value is None.
  68.  
  69.         suffix      -   A string that will be added at the end of each
  70.                         tweet (no starting space required). Pass None if
  71.                         you don't want a suffix. Default value is None.
  72.        
  73.         Returns
  74.        
  75.         tweet       -   A string with a maximum length of 140 characters.
  76.         """
  77.  
  78.         sl = 10
  79.         response = u''
  80.         while response == u'' or len(response) > 160:
  81.             # Generate some random text
  82.             response = self.generate_text(sl, seedword=seedword, \
  83.                 database=database, verbose=False, maxtries=100)
  84.             # Add the prefix
  85.             if prefix != None:
  86.                 response = u'%s %s' % (prefix, response)
  87.             # Add the suffix
  88.             if suffix != None:
  89.                 response = u'%s %s' % (response, suffix)
  90.             # Reduce the amount of words if the response is too long
  91.             if len(response) > 160:
  92.                 sl -= 1
  93.        
  94.         return response
  95.    
  96.    
  97.     def _error(self, methodname, msg):
  98.        
  99.         """Raises an Exception on behalf of the method involved.
  100.        
  101.         Arguments
  102.        
  103.         methodname  -   String indicating the name of the method that is
  104.                         throwing the error.
  105.        
  106.         message     -   String with the error message.
  107.         """
  108.        
  109.         raise Exception(u"ERROR in Markovbot.%s: %s" % (methodname, msg))
  110.  
  111.  
  112.     def _isalphapunct(self, string):
  113.        
  114.         """Returns True if all characters in the passed string are
  115.         alphabetic or interpunction, and there is at least one character in
  116.         the string.
  117.        
  118.         Allowed interpunction is . , ; : ' " ! ?
  119.        
  120.         Arguments
  121.        
  122.         string  -       String that needs to be checked.
  123.        
  124.         Returns
  125.        
  126.         ok          -   Boolean that indicates whether the string
  127.                         contains only letters and allowed interpunction
  128.                         (True) or not (False).
  129.         """
  130.        
  131.         if string.replace(u'.',u'').replace(u',',u'').replace(u';',u''). \
  132.             replace(u':',u'').replace(u'!',u'').replace(u'?',u''). \
  133.             replace(u"'",u'').isalpha():
  134.             return True
  135.         else:
  136.             return False
  137.    
  138.    
  139.     def _message(self, methodname, msg):
  140.        
  141.         """Prints a message on behalf of the method involved. Friendly
  142.         verion of self._error
  143.        
  144.         Arguments
  145.        
  146.         methodname  -   String indicating the name of the method that is
  147.                         throwing the error.
  148.        
  149.         message     -   String with the error message.
  150.         """
  151.        
  152.         print(u"MSG from Markovbot.%s: %s" % (methodname, msg))
  153.  
  154.  
  155.     def _triples(self, words):
  156.    
  157.         """Generate triplets from the word list
  158.         This is inspired by Shabda Raaj's blog on Markov text generation:
  159.         http://agiliq.com/blog/2009/06/generating-pseudo-random-text-with-markov-chains-u/
  160.        
  161.         Moves over the words, and returns three consecutive words at a time.
  162.         On each call, the function moves one word to the right. For example,
  163.         "What a lovely day" would result in (What, a, lovely) on the first
  164.         call, and in (a, lovely, day) on the next call.
  165.        
  166.         Arguments
  167.        
  168.         words       -   List of strings.
  169.        
  170.         Yields
  171.        
  172.         (w1, w2, w3)    -   Tuple of three consecutive words
  173.         """
  174.        
  175.         # We can only do this trick if there are more than three words left
  176.         if len(words) < 3:
  177.             return
  178.        
  179.         for i in range(len(words) - 2):
  180.             yield (words[i], words[i+1], words[i+2])
  181.  
  182.    
  183.     def _twitter_reconnect(self):
  184.        
  185.         """Logs in to Twitter, using the stored OAuth. This function is
  186.         intended for internal use, and should ONLY be called after
  187.         twitter_login has been called.
  188.         """
  189.        
  190.         # Report the reconnection attempt.
  191.         self._message(u'_twitter_reconnect', \
  192.             u"Attempting to reconnect to Twitter.")
  193.        
  194.         # Raise an Exception if the twitter library wasn't imported
  195.         if not IMPTWITTER:
  196.             self._error(u'_twitter_reconnect', u"The 'twitter' library could not be imported. Check whether it is installed correctly.")
  197.        
  198.         # Log in to a Twitter account
  199.         self._t = twitter.Twitter(auth=self._oauth)
  200.         self._ts = twitter.TwitterStream(auth=self._oauth)
  201.         self._loggedin = True
  202.        
  203.         # Get the bot's own user credentials
  204.         self._credentials = self._t.account.verify_credentials()
  205.        
  206.         # Report the reconnection success.
  207.         self._message(u'_twitter_reconnect', \
  208.             u"Successfully reconnected to Twitter!")
  209.    
  210.  
  211. os.path.realpath('./')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement