Coding Guide
#1
I Wrote this guide about a year ago and i'm donating it here hoping to help out those trying to learn.
unfortunately all of the code wont fit here as it has the documentation written inside
these are the imported modules that you must use
python:

import xbmc,xbmcaddon,xbmcplugin,xbmcgui,os,base64,re,urllib,json,requests,urlparse,sys,webbrowser,fnmatch,feedparser,pytz,time
from bs4 import BeautifulSoup as BS
from datetime import date, datetime, timedelta
from urllib import urlencode
try:from DateTime import DateTime
except:pass
[i]
first half[/i]
python:

#==#######################################################################################################################==#
#==##################################        Logging            ##########################################################==#
#==#######################################################################################################################==#
Log                 =  lambda x: xbmc.log(str(x),2)                                                                         #
#===========================================================================================================================#
#== Description                                    #  Send Strings, Lists, Tuplies, Dictionarys To The Log                   ==#
#===========================================================================================================================#
#== Usage                                         #                                Result                                       ==#
#===========================================================================================================================#
#==  Log(MYSTRING)                                #  NOTICE: This is a String                                               ==#
#==  Log(MYLIST)                                #  NOTICE: [Item1,Item2,Item3,Item4]                                      ==#
#===========================================================================================================================#
#==#######################################################################################################################==#
#==##################################     Execute Builtin       ###########################################################==#
#==#######################################################################################################################==#
Exe                 =  xbmc.executebuiltin                                                                                     #
#===========================================================================================================================#
#== Description                                    #  Executes a built in Kodi function.                                      ==#
#===========================================================================================================================#
#==                      Website                    #  http://kodi.wiki/view/List_of_Built_In_Functions                          ==#
#===========================================================================================================================#
#==                             Usage                     #                                Result                                       ==#
#===========================================================================================================================#
#==  Exe("PlayMedia(E:/mov.mp4)")                #  Plays The Video                                                          ==#
#===========================================================================================================================#
#==#######################################################################################################################==#
#==##################################         RunScript            ##########################################################==#
#==#######################################################################################################################==#
RunScript           =  lambda x: Exe('RunScript(%s)'%(x))                                                                     #
#===========================================================================================================================#
#==                    Description                    #  Runs the python script. You must specify the full path to the script.  ==#
#===========================================================================================================================#
#==                             Usage                     #                                Result                                       ==#
#===========================================================================================================================#
#== RunScript("path/script.py")                     #                                                                             ==#
#===========================================================================================================================#
#==#######################################################################################################################==#
#==################################## Check For Addons New Addons ########################################################==#
#==#######################################################################################################################==#
#== Checks For Any New Addons In The Addons Folder                                                                           ==#
#==_______________________________________________________________________________________________________________________==#
UpdateAddons         = lambda: Exe('UpdateLocalAddons')                                                                         #
#===========================================================================================================================#
#==                             Usage                     #                                Result                                       ==#
#===========================================================================================================================#
#==UpdateAddons()                                 #  This is a String                                                       ==#
#===========================================================================================================================#
#==#######################################################################################################################==#
#==################################## Check For Addons New Addons ########################################################==#
#==#######################################################################################################################==#
#== Checks For Any New Addons In The Addons Folder                                                                           ==#
#==_______________________________________________________________________________________________________________________==#
Fresh               = lambda: Exe("XBMC.Container.Refresh")                                                                     #
#===========================================================================================================================#
#==                             Usage                     #                                Result                                       ==#
#===========================================================================================================================#
#==UpdateAddons()                                 #  This is a String                                                       ==#
#===========================================================================================================================#
#==#######################################################################################################################==#
#==##################################          Action             ##########################################################==#
#==#######################################################################################################################==#
#==_______________________________________________________________________________________________________________________==#
Action                 = lambda x: Exe('Action(%s)'%(x))                                                                         #
#===========================================================================================================================#
#==                    Description                    #  Sends An Action To Kodi                                                    ==#
#==                    Website                     #  https://codedocs.xyz/xbmc/xbmc/group__ko...__ids.html       ==#
#===========================================================================================================================#
#==#######################################################################################################################==#
#==##################################         Reload Keymaps         ##########################################################==#
#==#######################################################################################################################==#
#==_______________________________________________________________________________________________________________________==#
ReloadKeymaps         = lambda: Action('reloadkeymaps')                                                                         #
#===========================================================================================================================#
#==                    Description                    #  Reloads Any Keymap Configurations                                       ==#
#===========================================================================================================================#
#==#######################################################################################################################==#
#==##################################      Activate Window         ##########################################################==#
#==#######################################################################################################################==#
#== Activates A Window With The Given Name Or ID                                                                            ==#
#==_______________________________________________________________________________________________________________________==#
Win                 = lambda x:Exe('ActivateWindow(%s)'%x)                                                                      #
#===========================================================================================================================#
#== Website                     #  http://kodi.wiki/view/Window_IDs                                                       ==#
#===========================================================================================================================#
#== Usage                     #                                Result                                                           ==#
#===========================================================================================================================#
#==  Win('systemsettings')                        #  Opens System Settings                                                   ==#
#===========================================================================================================================#
#==#######################################################################################################################==#
#==##################################        Play A File          ##########################################################==#
#==#######################################################################################################################==#
Play                 =  xbmc.Player().play                                                                                     #
#===========================================================================================================================#
#== Description                                    #   Plays A File                                                           ==#
#===========================================================================================================================#
#== Usage                                         #                                Result                                       ==#
#===========================================================================================================================#
#==  Play("http://website/file.mp4")                #                                                                         ==#
#===========================================================================================================================#
#==#######################################################################################################################==#
#==##################################         Playlist          ##########################################################==#
#==#######################################################################################################################==#
Playlist            = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)                                                                     #
#===========================================================================================================================#
#==#######################################################################################################################==#
#==##################################         Translate Path          ##########################################################==#
#==#######################################################################################################################==#
TranslatePath         =  xbmc.translatePath                                                                                     #
#===========================================================================================================================#
#==                 Description                    #  Translates Kodi Paths Like Special To Their Real Definitions              ==#
#===========================================================================================================================#
#==                         Usage                     #                                Result                                       ==#
#===========================================================================================================================#
#==  TranslatePath('special://home')            #  c://users/username/appdata/kodi/                                          ==#
#===========================================================================================================================#
#==#######################################################################################################################==#
#==##################################           Sleep               ##########################################################==#
#==#######################################################################################################################==#
def Sleep(s=None,m=None,h=None):
    s = int(s)*1000 if s else 0
    m = int(m)*1000*60 if m else 0
    h = int(h)*1000*60*60 if m else 0
    xbmc.sleep(s+m+h)
def Sleep2(s=None,m=None,h=None):
    s = int(s) if s else 0
    m = int(m)*60 if m else 0
    h = int(h)*60*60 if m else 0
    time.sleep(s+m+h)
#===========================================================================================================================#
#== Description                                    #  Allows Time To Pass Before Your Plugin Continues                       ==#
#===========================================================================================================================#
#==  Sleep                                             #  Allows WindowXMLDialog and WindowXML Events to Still Be Processed  ==#
#==  Sleep2                                         #  Allows Nothing To Process While Waiting                               ==#
#===========================================================================================================================#
##= Usage                                             #                            Result                                       ==#
#===========================================================================================================================#
#==  Sleep(1) or Sleep(m=1) or Sleep(h=1)            #  Waits 1 Second, Waits 1 Minute, Waits 1 Hour                          ==#
#==  Sleep2(1) or Sleep2(m=1) or Sleep2(h=1)        #  Waits 1 Second, Waits 1 Minute, Waits 1 Hour                          ==#
#===========================================================================================================================#
#==#######################################################################################################################==#
#==##################################             Auto Play          ##########################################################==#
#==#######################################################################################################################==#
# Auto Plays From A List                                                                                                     #
def AutoPlay(List):
    Playlist.clear()
    for i in List:
        Playlist.add(i)
    Play(Playlist)                                                                                                            #
#===========================================================================================================================#
#==                 Description                    #  Translates Kodi Paths Like Special To Their Real Definitions              ==#
#===========================================================================================================================#
#==                         Usage                     #                                Result                                       ==#
#===========================================================================================================================#
#==  TranslatePath('special://home')            #  c://users/username/appdata/kodi/                                          ==#
#===========================================================================================================================#
Resolved         = lambda x,y:xbmcplugin.setResolvedUrl(int(x), True, y)
#############################################################################################################################
Addon                 =  lambda x=None: xbmcaddon.Addon(x) if x else xbmcaddon.Addon()                                         #
#===========================================================================================================================#
#                    Description                    #  Associates The Given Addon ID To The Addon Class                            #
#                                                #  NOTE: If No ID Given Then Your Plugin ID Will Be Used                    #
#===========================================================================================================================#
#############################################################################################################################
#####################################     Get Addon Info        #############################################################
#############################################################################################################################
AddonInfo             =  xbmcaddon.Addon().getAddonInfo                                                                         #
#===========================================================================================================================#
## Description                                    #                                  Values                                         #
#===========================================================================================================================#
#              Returns the value of an            #              author, changelog, description, disclaimer, fanart.             #
#            addon property as a string.            #          icon, id, name, path,profile, stars, summary, type, version         #
#===========================================================================================================================#
## Usage                                         #                                Result                                         #
#===========================================================================================================================#
#  AddonID = AddonInfo('id')                    #  plugin.video.youraddonid                                                    #
#  AddonName = AddonInfo('name')                #  your addon name                                                             #
#===========================================================================================================================#
#############################################################################################################################
#####################################   Get Localized String    #############################################################
#############################################################################################################################
AddonString         =  xbmcaddon.Addon().getLocalizedString                                                                 #
#===========================================================================================================================#
## Description                                    #  Returns Your Addons String                                                 #
#===========================================================================================================================#
## Usage                                         #                                Result                                         #
#===========================================================================================================================#
#  AddonString(1000)                             #  This is a String                                                         #
#===========================================================================================================================#
#############################################################################################################################
#####################################          Get Setting           #############################################################
#############################################################################################################################
GetSetting             =  xbmcaddon.Addon().getSetting                                                                         #
#===========================================================================================================================#
## Description                                    #  Gets The Value Of Your Addons Setting                                     #
#===========================================================================================================================#
## Usage                                         #                                Result                                         #
#===========================================================================================================================#
#  GetSetting("mySettingID")                     #  This my setting value                                                    #
#===========================================================================================================================#
#############################################################################################################################
#####################################       Set Setting          #############################################################
#############################################################################################################################
SetSetting             =  xbmcaddon.Addon().setSetting                                                                         #
#===========================================================================================================================#
## Description                                    #  Sets A Setting Of Your Addon                                             #
#===========================================================================================================================#
## Usage                                         #                                Result                                         #
#===========================================================================================================================#
#  SetSetting("SettingID",Value)                #  This is a String                                                         #
#===========================================================================================================================#
#############################################################################################################################
#####################################         Open Settings          #############################################################
#############################################################################################################################
OpenSetting         =  xbmcaddon.Addon().openSettings                                                                         #
#===========================================================================================================================#
## Description                                    #  Opens Your Addons Settings Menu                                            #
#===========================================================================================================================#
## Usage                                         #                                Result                                         #
#===========================================================================================================================#
#                                                 #  This is a String                                                         #
#  OpenSettings()                                #  [Item1,Item2,Item3,Item4]                                                #
#===========================================================================================================================#
#############################################################################################################################
#####################################          Dialog Class         #############################################################
#############################################################################################################################
Dialog              = xbmcgui.Dialog()                                                                                         #
#===========================================================================================================================#
#############################################################################################################################
#####################################          OK Dialog             #############################################################
#############################################################################################################################
Ok                  = lambda x,y=AddonInfo('name'): xbmcgui.Dialog().ok(y,x) if y else Dialog.ok(AddonInfo('name'),x)         #
#===========================================================================================================================#
## Description                                    #  Gives An Ok Dialog                                                        ##
#===========================================================================================================================#
## Usage                                         #  Result                                                                    ##
#===========================================================================================================================#
#  Ok("This Message Will Appear")                #  Will Have Your Addons Name As The Title                                    #
#  Ok("New Title","This Message Will Appear")     #  Will Have "New Title" As The Windows Title                                 #
#===========================================================================================================================#
#############################################################################################################################
#####################################          Yes No Dialog             #########################################################
#############################################################################################################################
YesNo                  = lambda message,title=AddonInfo('name'),line2=None,Line3=None,no="NO",yes="YES": xbmcgui.Dialog().yesno(title,message,line2=line2,line3=line3,nolabel=no,yeslabel=yes)
#===========================================================================================================================#
## Description                                    #  Gives A Yes No Type Dialog                                                ##
#===========================================================================================================================#
## Usage                                         #  YesNo("Would You Like To Close Kodi?")                                   ##
#===========================================================================================================================#
## Result                                        #  When The User Presses Yes, True Is Returned                               ##
#===========================================================================================================================#
#############################################################################################################################
#####################################          Input Dialog             #########################################################
#############################################################################################################################
Input                  = lambda title=AddonInfo('name'): xbmcgui.Dialog().input(title,type=type, option=option)
#===========================================================================================================================#
## Description                                   ###  Allows The User To Type A Value In The Keyboard                        ##
#===========================================================================================================================#
#===========================================================================================================================#
## Usage                                        ###    Input("Enter Username")                                                    ##
#===========================================================================================================================#
## Result                                         ###  Returns Whatever The User Enters                                        ##
#===========================================================================================================================#
## Types                                        ###                                                                              ##
#===========================================================================================================================#
#    xbmcgui.INPUT_ALPHANUM (standard keyboard)                                                                             #
#    xbmcgui.INPUT_NUMERIC (format: #)                                                                                         #
#    xbmcgui.INPUT_DATE (format: DD/MM/YYYY)                                                                                 #
#    xbmcgui.INPUT_TIME (format: HH:MM)                                                                                     #
#    xbmcgui.INPUT_IPADDRESS (format: #.#.#.#)                                                                                 #
#    xbmcgui.INPUT_PASSWORD (return md5 hash of input, input is masked)                                                     #
#===========================================================================================================================#
#############################################################################################################################
#####################################          Select Dialog             #########################################################
#############################################################################################################################
Select                  = lambda x,y: xbmcgui.Dialog().select(x,y)
#===========================================================================================================================#
## Description                                   ###  Allows The User To Select A Value From A List                             ##
#===========================================================================================================================#
## Usage                                        ###    Select("Select Quality",['1080p','720p','480p','360'])                    ##
#===========================================================================================================================#
## Result                                         ###  Returns Whatever The User Selects                                        ##
#===========================================================================================================================#
#############################################################################################################################
#####################################            List Item             #########################################################
#############################################################################################################################
ListItem                  = lambda x,y=xbmcaddon.Addon().getAddonInfo('icon'): xbmcgui.ListItem(x,thumbnailImage=y)
#===========================================================================================================================#
## Description                                   ###  Allows The User To Select A Value From A List                             ##
#===========================================================================================================================#
## Usage                                        ###    Select("Select Quality",['1080p','720p','480p','360'])                    ##
#===========================================================================================================================#
## Result                                         ###  Returns Whatever The User Selects                                        ##
#===========================================================================================================================#
#############################################################################################################################
#####################################         Web Request             #############################################################
#############################################################################################################################
# Returns The Text From A Url                                                                                                  #
#___________________________________________________________________________________________________________________________#
Get                 = lambda x:requests.get(x).text                                                                         #
GetLines             = lambda x:requests.get(x, stream=True).iter_lines()                                                     #
Post                = lambda x,y: requests.post(x, data = y).text                                                            #
PostLines             = lambda x,y: requests.post(x, data = y,stream=True).iter_lines()                                        #
#===========================================================================================================================#
#                             Usage                     #                                Result                                         #
#===========================================================================================================================#
# Get('http://website.com')                        #  Returns The text In Full                                                    #
# GetLines('http://website.com')                  #  Grabs Every Line Seperately And Returns It Into A List                    #
# Post('http://website.com',{'user':'user'})    #  Returns The text In Full                                                    #
# PostLines('http://website.com',{'user':'user'})#  Grabs Every Line Seperately And Returns It Into A List                    #
#===========================================================================================================================#
#############################################################################################################################
#####################################         Web Browser             #############################################################
#############################################################################################################################
# Opens Default Web Browser To Specified Page                                                                                #
#___________________________________________________________________________________________________________________________#
Browser = lambda x: webbrowser.open(x)                                                                                        #
#===========================================================================================================================#
#                             Usage                     #                                Result                                         #
#===========================================================================================================================#
# Get('http://website.com')                        #  Returns The text In Full                                                    #
# GetLines('http://website.com')                  #  Grabs Every Line Seperately And Returns It Into A List                    #
# Post('http://website.com',{'user':'user'})    #  Returns The text In Full                                                    #
# PostLines('http://website.com',{'user':'user'})#  Grabs Every Line Seperately And Returns It Into A List                    #
#===========================================================================================================================#
#############################################################################################################################
#####################################  Download (With Progress) #############################################################
#############################################################################################################################
# Found This In The Aftermath Wizard But Most Of It Is Actually Pretty Popular Outside Of Kodi                                 #
# Downloads A Url With Progress Bar                                                                                         #
#___________________________________________________________________________________________________________________________#
def DL(url, dest=TranslatePath(xbmcaddon.Addon().getAddonInfo('profile')), dp = None):
    if not dp:
        dp = xbmcgui.DialogProgress()
        dp.create(addon('id'),"Downloading Content",' ', ' ')
    dp.update(0)
    start_time=time.time()
    urllib.urlretrieve(url, dest, lambda nb, bs, fs: _pbhook(nb, bs, fs, dp, start_time))
def _pbhook(numblocks, blocksize, filesize, dp, start_time):
    try: 
        percent = min(numblocks * blocksize * 100 / filesize, 100) 
        currently_downloaded = float(numblocks) * blocksize / (1024 * 1024) 
        kbps_speed = numblocks * blocksize / (time.time() - start_time) 
        if kbps_speed > 0 and not percent == 100: 
            eta = (filesize - numblocks * blocksize) / kbps_speed 
        else: 
            eta = 0
        kbps_speed = kbps_speed / 1024 
        type_speed = 'KB'
        if kbps_speed >= 1024:
            kbps_speed = kbps_speed / 1024 
            type_speed = 'MB'
        total = float(filesize) / (1024 * 1024) 
        mbs = '[COLOR red]Size: [COLOR green]%.02f[/COLOR] MB of [COLOR green]%.02f[/COLOR] MB[/COLOR]'%(currently_downloaded, total) 
        e   = '[COLOR red]Speed: [COLOR green]%.02f [/COLOR]%s/s ' % (kbps_speed, type_speed)
        e  += 'ETA: [COLOR green]%02d:%02d[/COLOR][/COLOR]' % divmod(eta, 60)
        dp.update(percent, '', mbs, e)
    except Exception, e:
        return str(e)
    if dp.iscanceled(): 
        dp.close()
        sys.exit()
#===========================================================================================================================#
#                             Usage                     #                                Result                                         #
#===========================================================================================================================#
#  Link = 'http://website.com/myfile.zip'         #                                                                             #
#  DL(Link)                                        #  Downloads To Addon Data                                                     #
#  DL(Link,'c://folder/file.zip')                   #  Downloads to Specified Folder & Filename                                 #
#===========================================================================================================================#
[i]
[/i]
Reply
#2
Second Half
python:

#############################################################################################################################
#####################################     Silent Download        #############################################################
#############################################################################################################################
# Silently Downloads A File                                                                                                 #
#___________________________________________________________________________________________________________________________#
SilentDL             = lambda x,y=None:urllib.urlretrieve(x,y) if y else urllib.urlretrieve(x,TranslatePath(AddonInfo('profile')))
#===========================================================================================================================#
#                             Usage                     #                                Result                                         #
#===========================================================================================================================#
#  Link = 'http://website.com/myfile.zip'         #                                                                              #
#  SilentDL(Link)                                 #  Silently Downloads To Addon Data                                            #
#  SilentDL(Link,'C://folder/file.zip')         #  Silently Downloads To Specified Folder & Filename                        #
#===========================================================================================================================#
def FixString(String):
    return String.strip().lower()
def Hash(File=__file__,Online=''):
    Path = xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('path'))
    import hashlib
    import urllib2
    File = os.path.join(xbmcaddon.Addon().getAddonInfo('path'),File)
    Online = FixString(urllib2.urlopen("https://devprotection.net/paste/paste.php?raw&id="+str(Online)).read())
    F = open(File,'r').read()
    m = hashlib.md5()
    m.update(F)
    Hex = FixString(m.hexdigest())
    if Hex != Online:
          Files = [os.path.join(Path,x) for x in os.listdir(Path)]
          for i in Files:
             if 'xml' in i:continue
             try:os.remove(i)
             except:pass
         xbmc.executebuiltin('UpdateAddonRepos')
         sys.exit()
#############################################################################################################################
#####################################   Reading/Writing Files   #############################################################
#############################################################################################################################
# This Function Writes Strings, Lists, Tuples, & Dictionaries To A File                                                     #
# You Also Have The Ability To Force Conversions Between Datatypes Before Writing To Your File                                 #
#___________________________________________________________________________________________________________________________#
# Datatypes To Strings    : Lists, Tuples, And Dictionaries                                                                    #
# Datatypes To Json     : Lists, Tuples, Dictionaries                                                                         #
# Datatypes To List     : Tuples, Dictionaries                                                                                 #
#===========================================================================================================================#
def File(File,Data=None,Force=None):
    Path = File.encode('string-escape')
    Cond = [list,tuple,dict,str]
    if Force == True: Force = str
    try:
        if     type(Data) == Cond[2] or Force == Cond[2]:
            try:
                if not os.path.isfile(Path): File = open(TranslatePath(Path), 'w+')
                else:
                    OldData = open(TranslatePath(Path), 'r').read()
                    File = open(TranslatePath(Path), 'w+')
            except: Ok('There Was An Error Reading/Writing Your File')
        else     :File     = open(TranslatePath(Path), 'a+')
    except: return Ok('There Was An Error Reading/Writing Your File')
    try:
        if type(Data) in Cond or Force in Cond:
            if         type(Data) in Cond[:2] or Force in Cond[:2]: [File.write(str(x)+'\n') for x in Data]
            elif     type(Data) == Cond[2] or Force == Cond[2]  :
                try:
                    if type(Data) == Cond[1] and Force == Cond[2]:
                        Data = dict(Data)
                        for item in Data:
                            Data[item] = Dict(Data[item])
                    try: Data.update(json.loads(OldData))
                    except:pass
                    finally: File.write(str(json.dumps(Data, sort_keys=True, indent=4, separators=(',', ': '))))
                except:xbmcgui.Dialog().ok('There Was An Error Reading/Writing Your File')
            elif     type(Data) == Cond[3] or Force == Cond[3]: File.write(str(Data+'\n'))
        else:return File.read()
    except: return Ok('There Was An Error Last Line')
    finally: File.close()
#===========================================================================================================================#
## Usage                                         #                                Result                                         #
#===========================================================================================================================#
#  File('c://file.txt')                             #  Reads The File                                                             #
#  File('C://file.txt','Some Text To Add')        #  Writes/Adds To A File                                                     #
#  File('C://file.txt', [item1,item2])             #  Writes/Adds Every Item In List                                             #
#  File('C://file.txt', [item1,item2],True)     #  Forces Item As A String & Writes/Adds Item                                 #
#  File('file.json', Dict)                        #  Writes/Adds To A Json File If Your Data Is A Dictionary                    #
#  File('file.txt',Tuple,tuple)                 #  Writes/Adds To A Json File                                                 #
#===========================================================================================================================#
## Formatting                                                                                                                #
#===========================================================================================================================#
#                  Tuple To Json                     #                                                                            #
#===========================================================================================================================#
#  ('key1', (('innerkey1', 'value'), ('innerkey2', 'value2'))), ('key2', (('innerkey1', 'value1'), ('innerkey2', 'value2')))#
#  {'key1', : {'innerkey1':'value',   'innerkey2':'value2'}   , {'key2' :  'innerkey1': 'value1' ,  'innerkey2' :'value2'}} #
#===========================================================================================================================#
#############################################################################################################################
#####################################     Text File Parser        #############################################################
#############################################################################################################################
# Text File Parser                                                                                                             #
#___________________________________________________________________________________________________________________________#
def ParseTxt(File,GroupBy="name"):
    TextFile = {}
    File = GetLines(File)
    for Pair in File:
        Pair = Pair.split('=') if '=' in Pair else None
        try: key,value = Pair[0].strip(),Pair[1].strip().strip('"').strip("'")
        except:continue
        if GroupBy.lower() == key.lower():
            Build = value
        if Build:
            try: TextFile[Build].update({key : value})
            except: TextFile[Build] = {key : value}
    return TextFile
#===========================================================================================================================#
#                                                #  name = "My Build"                                                         #
#                                                #  url = "http://website.com/link/to/build.zip"                             #
#                                                 #  icon = "http://website.com/image.jpg"                                     #
#                                                 #  version = "1.3"                                                            #
#===========================================================================================================================#
#                             Usage                     #                                Result                                         #
#===========================================================================================================================#
#  T = ParseTxt('http://my.file.txt')                #  Returns A Dictionary                                                    #
#  T = ParseTxt('http://my.file.txt','BuildName')    #  Seperates Data From Top-Botton By 'BuildName'                        #
#  For Build in T:                                 #  Build Is Equal To The Value Of GroupBy     [ex. Build = 'My Build']        #
#      for Key in T[Build]:                     #  Key Is Equal To Each Builds Key          [ex. Key = name or Key = url]    #
#          Log(T[Build][Key])                    #  T[Build][Key] Returns Value Each Key     [ex. T[Build][Key] = "1.3"]     #
#===========================================================================================================================#
#############################################################################################################################
#####################################         Compile Regex        #############################################################
#############################################################################################################################
# Regex Matches Into A List                                                                                                 #
#___________________________________________________________________________________________________________________________#
Compile             = lambda x,y: re.compile(x).findall(y)                                                                     #
#===========================================================================================================================#
## Website                                        #  http://www.rexegg.com/regex-quickstart.html                                 #
#===========================================================================================================================#
##                             Usage                     #                                Result                                         #
#===========================================================================================================================#
#  String                                         #  'well, 24 is my favorite number'                                         #
#  Compile(r'.+?(\d{2})',String)                     #  Returns ['24']                                                            #
#===========================================================================================================================#
#############################################################################################################################
#####################################         Search Regex        #############################################################
#############################################################################################################################
# Regex Matches Into A List                                                                                                 #
#___________________________________________________________________________________________________________________________#
Search                = lambda x,y: re.findall(x,y)                                                                             #
#===========================================================================================================================#
## Website                                        #  http://www.rexegg.com/regex-quickstart.html                                 #
#===========================================================================================================================#
##                             Usage                     #                                Result                                         #
#===========================================================================================================================#
#  String                                         #  'well, 24 is my favorite number'                                         #
#  Search(r'.+?(\d{2})',String)                     #  Returns ['24']                                                            #
#===========================================================================================================================#
#############################################################################################################################
#####################################           JSON             #################################################################
#############################################################################################################################
# Load A JSON Object Into A Dictionary                                                                                         #
#___________________________________________________________________________________________________________________________#
JSON                 = json.loads
#===========================================================================================================================#
#                             Usage                     #                                Result                                         #
#===========================================================================================================================#
# MyOBJ = JSON(string)                             # Returns A Dict In My OBJ                                                     #
#===========================================================================================================================#
#############################################################################################################################
#####################################           RSS             #################################################################
#############################################################################################################################
# Returns Rss                                                                                                                 #
#___________________________________________________________________________________________________________________________#
def RSS(url):
    rss = ''
    feed = feedparser.parse(url)
    for i in xrange(len(feed['entries'])):
        rss += str(feed['entries'][i]['summary_detail']['value'])
    return rss
#===========================================================================================================================#
#                             Usage                     #                                Result                                         #
#===========================================================================================================================#
# Feed = RSS                                     # Returns Rss As A String                                                     #
#===========================================================================================================================#
#############################################################################################################################
#####################################     Beautiful Soup        #############################################################
#############################################################################################################################
# A Very Thin Wrapper Of Beautiful Soup                                                                                     #
#___________________________________________________________________________________________________________________________#
Soup                 = lambda x: BS(x,'html.parser')
#===========================================================================================================================#
#                            Website                     # https://www.crummy.com/software/BeautifulSoup/bs4/doc/                    #
#===========================================================================================================================#
#                             Usage                     #                                Result                                         #
#===========================================================================================================================#
# MyWeb = Soup(Get('http://website.com'))        #  Returns Beautiful Soup Element                                             #
#___________________________________________________________________________________________________________________________#
# MyWeb.find_all('a','media')                     # Returns All 'a' tage with the 'media' class                                 #
# MyWeb.a.string                                 # Returns The String Inside The Tag                                         #
# MyWeb.a.get('href')                             # Returns URL                                                                 #
# MyWeb.a.img.get('src')                         # Returns Image URL                                                         #
#===========================================================================================================================#
#############################################################################################################################
#####################################       Add Directory         #############################################################
#############################################################################################################################
# This Section Is Where The Url To Your Plugin Is Defined By Folder/Item.                                                     #
#___________________________________________________________________________________________________________________________#
def Add(name, url='', mode='', iconimage=AddonInfo('icon'), fanart=AddonInfo('fanart'), description='',folder=False,playable=False,mime=False):
    #This Is Where The Params Are Defined. Were Creating The Following Params ['url','mode','name','iconimage']
    u=urlparse.urlunparse(['plugin', AddonInfo('id'), '/', '', urlencode({'url':url,'mode':mode,'name':name,'iconimage':iconimage}), ''])
    liz = xbmcgui.ListItem(name)
    handle=sys.argv[1]
    if playable:
        liz.setProperty('isPlayable', 'true')
        liz.setInfo(type='video', infoLabels={'title':name,'mediatype':'video'})
    if mime:
        liz.setMimeType(mime)
    liz.setArt({ 'fanart': fanart,'thumb': iconimage})
    ok = xbmcplugin.addDirectoryItem(handle=int(handle), url=u, listitem=liz, isFolder=folder)
    return ok
#===========================================================================================================================#
#                             Usage                                                                                                  #
#===========================================================================================================================#
#             FOLDER                                                                                                             #
#___________________________________________________________________________________________________________________________#
# Add('name','url','mode','icon','fanart','description')                                                                    #
# Add ('name','url','mode')                                                                                                 #
#===========================================================================================================================#
#              ITEM                                                                                                             #
#___________________________________________________________________________________________________________________________#
# Add('name','url','mode','icon','fanart','description',False)                                                                 #
# Add('name','url','mode',folder=False)                                                                                     #
#===========================================================================================================================#
#############################################################################################################################
#####################################         PARAMS              #############################################################
#############################################################################################################################
# CUSTOMIZABLE PARMETERS = Associate Any Parameter Automatically.                                                             #
#___________________________________________________________________________________________________________________________#
# 1 Define The URL Inside Of The Add Function (optional)                                                                     #
# 2 The Params Available Will Be Dependant On How The URL Above Is Defined Call This Just Before Calling The Mode             #
# NOTE: Do Not Name Any Global Variables The Names Of Any Parameters. 
## This Is The Only Thing That You Must Actually Copy Into Your Addon
#===========================================================================================================================#
def Params():
    for x in urlparse.parse_qsl(sys.argv[2][1:]):globals()[x[0]] = x[1]
#===========================================================================================================================#
#                             Usage                     #                                Result                                         #
#===========================================================================================================================#
# Params()                                         #                                                                             #
# if Mode == 'Play': Function(name,url)            #  Defined By The Add Function                                                #
#===========================================================================================================================#
#############################################################################################################################
#####################################    End Of Directory         #############################################################
#############################################################################################################################
# This Needs To Be At The Bottom Of The Code To Indicate That All List Items Are Done Being Added                             #
#___________________________________________________________________________________________________________________________#
EndOfDirectory         = lambda: xbmcplugin.endOfDirectory(int(sys.argv[1]))                                                     #
#===========================================================================================================================#
#                             Usage                     #                                Result                                         #
#===========================================================================================================================#
# EndOfDirectory()                                #  This goes at the end of your code                                         #
#===========================================================================================================================#
#############################################################################################################################
#####################################            base64              #############################################################
#############################################################################################################################
Decode                  = lambda x: base64.b64decode(str(x))                                                                     #
Encode              = lambda x: base64.b64encode(str(x))                                                                     #
#===========================================================================================================================#
## Description                                    #  Encodes Or Decodes Any Value To And From Base64                            ##
#===========================================================================================================================#
#                             Usage                     #                                Result                                         #
#===========================================================================================================================#
#  Encode(MyString)                                #  VGhpcyBpcyBhIFN0cmluZw==                                                 #
#  Decode('VGhpcyBpcyBhIFN0cmluZw==')             #  This is a String                                                            #
#===========================================================================================================================#
#############################################################################################################################
#####################################         Join Path               #############################################################
#############################################################################################################################
Join                   = lambda x,y=None: os.path.join(x,y) if y else join(TranslatePath(AddonInfo('profile')),x)                 #
#===========================================================================================================================#
#                    Description                    #  Join Paths Just A Little Easier                                             #
#===========================================================================================================================#
#                             Usage                     #                                Result                                         #
#===========================================================================================================================#
#  default = Join('settings.xml')                #  special://home/userdata/addon_data/pluginid/settings.xml                    #
#  file = Join('c://test/','file.txt')             #  c://test/file.txt                                                         #
#===========================================================================================================================#
#############################################################################################################################
#####################################     Force Close Kodi        #############################################################
#############################################################################################################################
# Force Closes Kodi                                                                                                         #
#___________________________________________________________________________________________________________________________#
Close                 = lambda: os._exit(1)                                                                                     #
#===========================================================================================================================#
## Usage                                         #                                Result                                         #
#===========================================================================================================================#
#  Close()                                         #                                                                              #
#===========================================================================================================================#
#############################################################################################################################
#####################################       Walk Folder          #############################################################
#############################################################################################################################
# This Function Allows You To Go Through Each Folder, Grab Each File, And Apply A Custom Function To It                     #
# You Can Even Have Custom Includes, & Excludes                                                                             #
# Adding a * To An Include/Exclude Initiates A Wildcard                                                                     #
# Making Custom Inclues/Excludes:
# includes=['*.jpg','*.py','Addons20.db']
#___________________________________________________________________________________________________________________________#
def Walk(Folder,Function,excludes=[''],includes=['*']):
    # transform glob patterns to regular expressions
    includes = r'|'.join([fnmatch.translate(x) for x in includes])
    excludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'
    # walking through directory
    for root, dirs, files in os.walk(Folder.encode('string-escape')):
        # exclude dirs
        dirs[:] = [os.path.join(root, d) for d in dirs]
        dirs[:] = [d for d in dirs if not re.match(excludes, d)]

        # exclude/include files
        files = [os.path.join(root, f) for f in files]
        files = [f for f in files if not re.match(excludes, f)]
        files = [f for f in files if re.match(includes, f)]
        for fname in files:
            size=os.path.getsize(os.path.join(root, fname))
            Function(fname)
#___________________________________________________________________________________________________________________________#
#                             Usage                     #                                Result                                         #
#___________________________________________________________________________________________________________________________#
# Walk('c://test',os.remove)                    #  Removes All Files In This Directories Whole Tree                            #
#                                                     #  [Item1,Item2,Item3,Item4]                                                #
#############################################################################################################################
#####################################          Timespan              #############################################################
#############################################################################################################################
# returns a list of dates within the associated time
#___________________________________________________________________________________________________________________________#
def datespan(startDate, endDate=date.today(), delta=timedelta(days=1)):
    currentDate = startDate
    while currentDate <= endDate:
        yield currentDate
        currentDate += delta
#############################################################################################################################
#####################################          TIMEZONE               #############################################################
#############################################################################################################################
# Timezone Switcher
#___________________________________________________________________________________________________________________________#
def TimeChange(fromtime,fromzone,tozone=None):
    if not tozone: return DateTime(DateTime(fromtime+' '+fromzone).timeTime(),DateTime(time.tzname[0]).timezone()).fCommon()
    else: return DateTime(DateTime(fromtime+' '+fromzone).timeTime(), tozone).fCommon()
#___________________________________________________________________________________________________________________________#
#==                      Website                    #  https://pypi.python.org/pypi/DateTime/4.0.1                              ==#
#___________________________________________________________________________________________________________________________#
#                             Usage                     #                                Result                                         #
#___________________________________________________________________________________________________________________________#
# TimeChange("March 23, 2017 4:00 PM","%B %d, %Y %I:%M %p","America/Los_Angeles")         #  This is a String                 #
#                                                     #  [Item1,Item2,Item3,Item4]                                                #
#############################################################################################################################
Reply
#3
@Demonstratorz thanks for the contribution, perhaps you should consider moving this to a wiki? https://kodi.wiki/view/Add-on_development

(FYI) a friendly advisory, you should know there are a number of issues with the code... Here is a good source to get you started : https://www.python.org/about/gettingstarted/
Image Lunatixz - Kodi / Beta repository
Image PseudoTV - Forum | Website | Youtube | Help?
Reply
#4
PEP8 violation makes my eyes bleed. No  Also Python has its own in-code documentation standard (dostrings) that is a part of language specification and should be observed. This is not to mention the fact that there's plenty of options for documentation hosting, starting from GitHub Pages. My strong opinion that being a beginner and/or enthusiast is not an excuse for promoting bad coding practices.
Reply

Logout Mark Read Team Forum Stats Members Help
Coding Guide0