Advertisement
Darksider3

Untitled

Feb 21st, 2014
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.92 KB | None | 0 0
  1. #!/usr/bin/env python2.7
  2. #
  3. # * statusnetbot.py - A simple Bot for StatusNet. Viewing Personal-Timeline
  4. # *                   , Posting and some more(see README(only German Version yet!))
  5. # *
  6. # *
  7. # * Copyright 2014 Leon Giesenk&auml;mper <leon@darksider3.de>
  8. # *
  9. # * This program is free software; you can redistribute it and/or modify
  10. # * it under the terms of the GNU General Public License as published by
  11. # * the Free Software Foundation; either version 3 of the License, or
  12. # * (at your option) any later version.
  13. # *
  14. # * This program is distributed in the hope that it will be useful,
  15. # * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17. # * GNU General Public License for more details.
  18. # *
  19. # * You should have received a copy of the GNU General Public License
  20. # * along with this program; if not, write to the Free Software
  21. # * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  22. # * MA 02110-1301, USA.
  23. # *
  24. # * ADITIONAL LICENSE RULE BY THE AUTHOR OF THIS SOFTWARE:
  25. # * THIS SERVER HAS NO LICENSE FOR MILITARY USE. ANY USE
  26. # * OF THIS SOFTWARE FROM/FOR MILITARY, (SECRET-)INTELLIGENCE AGENCYS/SERVICES
  27. # * AND GOVERNMENTS (LIKE THEU USA, GERMANY(THESE ONLY EXAMPLES!)) USE
  28. # * IS STRICTLY FORBIDDEN BY LAW, CREATED
  29. # * WITH THAT ADDITIONAL RULE! YOU FIND THIS RULE IN THE LICENSE FILE TOO.
  30. # * --PS: And no, there isnt any way to get a license for that.
  31. #Used actually:
  32. #  * urllib(2)
  33. #  * re
  34. #  * shelve - self like pdb
  35. #  * sys - used with pdb&shelve
  36. #  * pdb - not really used, features is being implemented
  37. #  * json or simplejson as json
  38. #  * conf (conf.py in working directory)
  39. #  -feedparser is unused at the moment
  40. ########################################################################
  41. #Actually Variables:
  42. #  * ACC_NICK
  43. #  * ACC_PASSWORD
  44. #  * SERVER(https://example.com)
  45. #  * VERSION
  46. #  * URL_SHORTENER_LOGIN
  47. #  * URL_SHORTENER_PASSWORD
  48. #  * DATABASE_FILE
  49. #  * BOTNAME
  50.  
  51.  
  52. import urllib, urllib2
  53. #import urlib, urllib.request as urllib2
  54. import re
  55. import sys
  56. import shelve
  57. import pdb
  58. import feedparser
  59. from StringIO import StringIO
  60. #import json
  61. try:
  62.   import json
  63. except ImportError:
  64.   import simplejson as json
  65. #conf.py
  66. try:
  67.   import conf
  68. except ImportError:
  69.   print( "Cant import 'conf.py'. Please create it, befor you retry!")
  70.   sys.exit(1)
  71.  
  72.  
  73. ###Allgemeiner Service
  74.  
  75.  
  76.  
  77. class Service(object):
  78.   def __init__(self):
  79.     print ("+++Using Server "+conf.SERVER+"+++")
  80.  
  81.   def post(self, msg, source="pyStatusNetBot"):
  82.     url = "https://"+conf.SERVER+"/api/statuses/update.json"
  83.     ###
  84.     #(1)HTTPBasicAuthHandler is a handler for Apache2 .htaccess
  85.     #files. Its just manages with the object(here auth_handler)
  86.     #the authentications.
  87.     ###
  88.     #HTTPPasswordMgrWithDefaultRealm()) is (like) a cache:
  89.     #and handles later if it gets a add_password over the object, and waits
  90.     #then for an action with urlopen(It uses the password if needed and definied)
  91.     auth_handler = urllib2.HTTPBasicAuthHandler(urllib2.HTTPPasswordMgrWithDefaultRealm())
  92.  
  93.  
  94.     #Adds a password to the AuthHandler[1], the realm(first argument) is the auth-window
  95.     #that shows the realm, beispiel: "Server XYZ"
  96.     auth_handler.add_password(None, url, conf.ACC_NICK, conf.ACC_PASSWORD)
  97.  
  98.  
  99.     #build_opener handles a "OpenerDirector" instance. Its just
  100.     #here a HTTPHandler
  101.     opener = urllib2.build_opener(auth_handler)
  102.  
  103.  
  104.     #Install it as default opener("install_opener")
  105.     urllib2.install_opener(opener)
  106.  
  107.  
  108.     #Encode send URL to conform URI
  109.     data = urllib.urlencode({'status': msg.encode('utf-8'),\
  110.      'source': source+conf.VERSION})
  111.     print( "---DataEncoded "+data+" ---")
  112.  
  113.  
  114.     #Send data to url
  115.     open_handler = urllib2.urlopen(url, data)
  116.  
  117.  
  118.     #load JSON-Response into response
  119.     response=json.load(open_handler)
  120.  
  121.     #if the key "error" exists, print out and exit
  122.     if (response.has_key("error")) == 1:
  123.       print ("Error: ")
  124.       print (response)
  125.       print ("Please correct it. Often its only a problem with your Username/Password")
  126.       print ("In the conf.py file.")
  127.       sys.exit(1)
  128.     #Close
  129.     open_handler.close()
  130.     return response
  131.  
  132.  
  133. ####Shortener
  134.  
  135.  
  136.  
  137. #Dont works yet - API has changed(seems like)
  138. class Shortener(object):
  139.   #sandbox isnt good
  140.   sandbox = False
  141.  
  142.   def run(self, item, text):
  143.     if(len(text) < 120) == 0:
  144.       url = "http://pastebin.com/api/api_post.php"
  145.       data = urllib.urlencode({"api_dev_key": conf.API_KEY,\
  146.               "api_user_key": conf.API_KEY_USER,\
  147.               "api_paste_format": "text", \
  148.               "api_option": "paste", \
  149.               "api_paste_code": text})
  150.       print "Pasting to pastebin.com "+data
  151.       opened = urllib2.urlopen(url, data)
  152.       sourceurl=opened.read()
  153.       item=sourceurl
  154.       opened.close()
  155.     #tr.im api is f*cking easy, yeah!
  156.     url = "http://is.gd/create.php"
  157.     data=({"format": "json", "url": item})
  158.     #Exists these variables?
  159.     #if(conf.URL_SHORTENER_LOGIN != '' and conf.URL_SHORTENER_PASSWORD != ''):
  160.       #Add Username/Password to url, dont encode for valid output ;-)
  161.       #url += "&username=" + conf.URL_SHORTENER_LOGIN + "&password=" + \
  162.       #conf.URL_SHORTENER_PASSWORD
  163.     #if you really want it... you get it.
  164.     #if self.sandbox:
  165.     #  url += "&sandbox=true"
  166.     #open and get response
  167.     print "Retriving URLShortn"
  168.     opened = urllib2.urlopen(url,data)
  169.     response = json.load(opened)
  170.     #close
  171.     opened.close()
  172.     #return the url
  173.     print "returning response"
  174.     return {"shorturl": response['shorturl'], "pasteUrl": response['pasteUrl']}
  175.  
  176.  
  177. ###Definition General
  178.  
  179.  
  180.  
  181. #Write it into Services()?!
  182. def escape_html_tags(data):
  183.   #Escape all html tags
  184.   p = re.compile(r'<(.*?)>')
  185.   return p.sub('&lt;\\1&gt;', data)
  186. def build_msg(item, shorturl, prefix=''):
  187.   message = prefix + item['title'] + item['content']
  188.   message = escape_html_tags(message)
  189.   mlen = 140 - len(shorturl) - 4
  190.   message = message[0:mlen]
  191.   if (len(message) < 120) == 0:
  192.     message += "... " + shorturl
  193.   return message
  194.  
  195.  
  196. def main():
  197.   #init Service()
  198.   service=Service()
  199.  
  200.   #open Database
  201.  
  202.   db = shelve.open(conf.DATABASE_FILE, writeback=True)
  203.   try:
  204.     if type(db['posted_items']) != list:
  205.       db['posted_items'] = []
  206.   except KeyError:
  207.     db['posted_items'] = []
  208.   #Build item
  209.  
  210.   print ("+++Building Message+++")
  211.   dbitem={"title":"", "content": "This message is posted by @darksider3 s <"+\
  212.   conf.BOTNAME+">+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"}
  213.   short=Shortener()
  214.   shortcut=short.run("www.darksider3.de", dbitem["content"])
  215.   #build message
  216.   item=build_msg(dbitem, shortcut)
  217.  
  218.   #post Message
  219.   print("+++Posting "+item+"+++")
  220.  
  221.   #and print out some specifics things
  222.  
  223.   print (service.post(item)["created_at"])
  224.   #close the database(clean exit)
  225.  
  226.   db.close()
  227.   return 0
  228. if __name__ == "__main__":
  229.   sys.exit(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement