Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python2.7
- #
- # * statusnetbot.py - A simple Bot for StatusNet. Viewing Personal-Timeline
- # * , Posting and some more(see README(only German Version yet!))
- # *
- # *
- # * Copyright 2014 Leon Giesenkämper <leon@darksider3.de>
- # *
- # * This program is free software; you can redistribute it and/or modify
- # * it under the terms of the GNU General Public License as published by
- # * the Free Software Foundation; either version 3 of the License, or
- # * (at your option) any later version.
- # *
- # * This program is distributed in the hope that it will be useful,
- # * but WITHOUT ANY WARRANTY; without even the implied warranty of
- # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- # * GNU General Public License for more details.
- # *
- # * You should have received a copy of the GNU General Public License
- # * along with this program; if not, write to the Free Software
- # * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
- # * MA 02110-1301, USA.
- # *
- # * ADITIONAL LICENSE RULE BY THE AUTHOR OF THIS SOFTWARE:
- # * THIS SERVER HAS NO LICENSE FOR MILITARY USE. ANY USE
- # * OF THIS SOFTWARE FROM/FOR MILITARY, (SECRET-)INTELLIGENCE AGENCYS/SERVICES
- # * AND GOVERNMENTS (LIKE THEU USA, GERMANY(THESE ONLY EXAMPLES!)) USE
- # * IS STRICTLY FORBIDDEN BY LAW, CREATED
- # * WITH THAT ADDITIONAL RULE! YOU FIND THIS RULE IN THE LICENSE FILE TOO.
- # * --PS: And no, there isnt any way to get a license for that.
- #Used actually:
- # * urllib(2)
- # * re
- # * shelve - self like pdb
- # * sys - used with pdb&shelve
- # * pdb - not really used, features is being implemented
- # * json or simplejson as json
- # * conf (conf.py in working directory)
- # -feedparser is unused at the moment
- ########################################################################
- #Actually Variables:
- # * ACC_NICK
- # * ACC_PASSWORD
- # * SERVER(https://example.com)
- # * VERSION
- # * URL_SHORTENER_LOGIN
- # * URL_SHORTENER_PASSWORD
- # * DATABASE_FILE
- # * BOTNAME
- import urllib, urllib2
- #import urlib, urllib.request as urllib2
- import re
- import sys
- import shelve
- import pdb
- import feedparser
- from StringIO import StringIO
- #import json
- try:
- import json
- except ImportError:
- import simplejson as json
- #conf.py
- try:
- import conf
- except ImportError:
- print( "Cant import 'conf.py'. Please create it, befor you retry!")
- sys.exit(1)
- ###Allgemeiner Service
- class Service(object):
- def __init__(self):
- print ("+++Using Server "+conf.SERVER+"+++")
- def post(self, msg, source="pyStatusNetBot"):
- url = "https://"+conf.SERVER+"/api/statuses/update.json"
- ###
- #(1)HTTPBasicAuthHandler is a handler for Apache2 .htaccess
- #files. Its just manages with the object(here auth_handler)
- #the authentications.
- ###
- #HTTPPasswordMgrWithDefaultRealm()) is (like) a cache:
- #and handles later if it gets a add_password over the object, and waits
- #then for an action with urlopen(It uses the password if needed and definied)
- auth_handler = urllib2.HTTPBasicAuthHandler(urllib2.HTTPPasswordMgrWithDefaultRealm())
- #Adds a password to the AuthHandler[1], the realm(first argument) is the auth-window
- #that shows the realm, beispiel: "Server XYZ"
- auth_handler.add_password(None, url, conf.ACC_NICK, conf.ACC_PASSWORD)
- #build_opener handles a "OpenerDirector" instance. Its just
- #here a HTTPHandler
- opener = urllib2.build_opener(auth_handler)
- #Install it as default opener("install_opener")
- urllib2.install_opener(opener)
- #Encode send URL to conform URI
- data = urllib.urlencode({'status': msg.encode('utf-8'),\
- 'source': source+conf.VERSION})
- print( "---DataEncoded "+data+" ---")
- #Send data to url
- open_handler = urllib2.urlopen(url, data)
- #load JSON-Response into response
- response=json.load(open_handler)
- #if the key "error" exists, print out and exit
- if (response.has_key("error")) == 1:
- print ("Error: ")
- print (response)
- print ("Please correct it. Often its only a problem with your Username/Password")
- print ("In the conf.py file.")
- sys.exit(1)
- #Close
- open_handler.close()
- return response
- ####Shortener
- #Dont works yet - API has changed(seems like)
- class Shortener(object):
- #sandbox isnt good
- sandbox = False
- def run(self, item, text):
- if(len(text) < 120) == 0:
- url = "http://pastebin.com/api/api_post.php"
- data = urllib.urlencode({"api_dev_key": conf.API_KEY,\
- "api_user_key": conf.API_KEY_USER,\
- "api_paste_format": "text", \
- "api_option": "paste", \
- "api_paste_code": text})
- print "Pasting to pastebin.com "+data
- opened = urllib2.urlopen(url, data)
- sourceurl=opened.read()
- item=sourceurl
- opened.close()
- #tr.im api is f*cking easy, yeah!
- url = "http://is.gd/create.php"
- data=({"format": "json", "url": item})
- #Exists these variables?
- #if(conf.URL_SHORTENER_LOGIN != '' and conf.URL_SHORTENER_PASSWORD != ''):
- #Add Username/Password to url, dont encode for valid output ;-)
- #url += "&username=" + conf.URL_SHORTENER_LOGIN + "&password=" + \
- #conf.URL_SHORTENER_PASSWORD
- #if you really want it... you get it.
- #if self.sandbox:
- # url += "&sandbox=true"
- #open and get response
- print "Retriving URLShortn"
- opened = urllib2.urlopen(url,data)
- response = json.load(opened)
- #close
- opened.close()
- #return the url
- print "returning response"
- return {"shorturl": response['shorturl'], "pasteUrl": response['pasteUrl']}
- ###Definition General
- #Write it into Services()?!
- def escape_html_tags(data):
- #Escape all html tags
- p = re.compile(r'<(.*?)>')
- return p.sub('<\\1>', data)
- def build_msg(item, shorturl, prefix=''):
- message = prefix + item['title'] + item['content']
- message = escape_html_tags(message)
- mlen = 140 - len(shorturl) - 4
- message = message[0:mlen]
- if (len(message) < 120) == 0:
- message += "... " + shorturl
- return message
- def main():
- #init Service()
- service=Service()
- #open Database
- db = shelve.open(conf.DATABASE_FILE, writeback=True)
- try:
- if type(db['posted_items']) != list:
- db['posted_items'] = []
- except KeyError:
- db['posted_items'] = []
- #Build item
- print ("+++Building Message+++")
- dbitem={"title":"", "content": "This message is posted by @darksider3 s <"+\
- conf.BOTNAME+">+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"}
- short=Shortener()
- shortcut=short.run("www.darksider3.de", dbitem["content"])
- #build message
- item=build_msg(dbitem, shortcut)
- #post Message
- print("+++Posting "+item+"+++")
- #and print out some specifics things
- print (service.post(item)["created_at"])
- #close the database(clean exit)
- db.close()
- return 0
- if __name__ == "__main__":
- sys.exit(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement