Advertisement
MRtecno98

SfondiPaper Channel Bot ALPHA 1.1.2

Dec 27th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.01 KB | None | 0 0
  1. import telepot , random , pprint , requests , json , random , os , sys , time
  2. from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup , InlineKeyboardButton
  3.  
  4. token = "XXXXXX"
  5. bot = None
  6. msginfo = None
  7. action = None
  8. message = None
  9.  
  10. admins = [212546200 , 144218415]
  11.  
  12. assocs = {}
  13. inqueque = []
  14.  
  15. server = "http://sfondipaper.altervista.org"
  16. folder = "/"
  17.  
  18. def debug(chatid) :
  19.     sendImageNotCompressed(chatid , "http://www.sfondipaper.altervista.org/categories/os/test.png")
  20.     return
  21.  
  22. def sendImageNotCompressed(chatid , url) :
  23.     checkWorkDir()
  24.     request = requests.get(url)
  25.     request.raise_for_status()
  26.     with open("." + os.sep + "work" + os.sep + os.path.basename(url) , "wb") as file :
  27.         for chunk in request.iter_content(10000) :
  28.             file.write(chunk)
  29.     with open("." + os.sep + "work" + os.sep + os.path.basename(url) , "rb") as file :
  30.         bot.sendDocument(chatid , file)
  31.     return
  32.  
  33. def checkWorkDir() :
  34.     os.makedirs("work" , exist_ok=True)
  35.  
  36. def menu(chatid) :
  37.     sended = sendAndLog(chatid , "Benvenuto, " + message["from"]["first_name"] + " questo è il bot di @sfondipaper!" ,
  38.                              reply_markup=ReplyKeyboardMarkup(
  39.                                     keyboard=[
  40.                                         [KeyboardButton(text="Categorie"),
  41.                                          KeyboardButton(text="Parla con me"),],
  42.                                         [KeyboardButton(text="Sfondo del mese"),
  43.                                          KeyboardButton(text="Sfondo Pack zip")],
  44.                                         [KeyboardButton(text="Mandaci il tuo sfondo preferito!")]
  45.                                     ]
  46.                                  ))
  47.  
  48. def categories(chatid) :
  49.     cat = getCategoriesList()
  50.     names = list(cat.keys())
  51.     for n in names :
  52.         names[names.index(n)] = KeyboardButton(text=n)
  53.     result = []
  54.     while len(names) != 0 :
  55.         result.append(names[:3])
  56.         del names[:3]
  57.     result.append([KeyboardButton(text="Menu")])
  58.     sended = sendAndLog(chatid , "Scegli una categoria per vedere gli sfondi",
  59.                              reply_markup=ReplyKeyboardMarkup(
  60.                                  keyboard=result
  61.                              )
  62.                            )
  63.  
  64. def getCategoriesList() :
  65.     request = requests.get(server + folder + "categories/categories.json")
  66.     request.raise_for_status()
  67.     txt = request.text
  68.     obj = json.loads(txt)
  69.     return obj
  70.  
  71. def getCategory(category) :
  72.     url = ""
  73.     if category == "all" :
  74.         url = "/all.json"
  75.     else :
  76.         url = "/" + category + "/list.json"
  77.  
  78.     request = requests.get(server + folder + "categories" + url)
  79.     request.raise_for_status()
  80.     text = request.text
  81.     obj = json.loads(text)
  82.     return obj
  83.  
  84. def sendAndLog(chatid , \
  85.                text, \
  86.                parse_mode=None, \
  87.                disable_web_page_preview=None, \
  88.                disable_notification=None, \
  89.                reply_to_message_id=None, \
  90.                reply_markup=None) :
  91.     global bot
  92.     bot.sendMessage(chatid, \
  93.                     text, parse_mode=parse_mode, \
  94.                     disable_web_page_preview=disable_web_page_preview, \
  95.                     disable_notification=disable_notification, \
  96.                     reply_to_message_id=reply_to_message_id, \
  97.                     reply_markup=reply_markup)
  98.     print("#" + str(action) + "\tRisposta: " + text)
  99.  
  100. def listLower(l) :
  101.     for i in l :
  102.         l[l.index(i)] = i.lower()
  103.     return l
  104.  
  105. def handle(msg) :
  106.     global bot
  107.     global chatid
  108.     global action
  109.     global msginfo
  110.     global message
  111.  
  112.     #pprint.pprint(msg)
  113.  
  114.     try :
  115.         bot.getMe()
  116.     except :
  117.         sys.exit(0)
  118.    
  119.     action = random.randint(1,99999)
  120.     msginfo = telepot.glance(msg)
  121.     chatid = msginfo[2]
  122.     message = msg
  123.     categoriesList = getCategoriesList()
  124.  
  125.     if msginfo[0] == "text" :
  126.         print("#" + str(action) + "\t" + str(chatid) + " scrive: " + msg["text"])
  127.         txt = msg["text"].lower().replace("/","")
  128.     else :
  129.         print("#" + str(action) + "\t" + str(chatid) + " invia un dato")
  130.  
  131.     if chatid in inqueque :
  132.         if not msginfo[0] == "document" :
  133.             if txt == "torna al menu" :
  134.                 inqueque.remove(chatid)
  135.                 menu(chatid)
  136.             else :
  137.                 sendAndLog(chatid , "Invia l'immagine in formato file" , reply_markup=ReplyKeyboardMarkup(
  138.                         [[KeyboardButton(text="Torna al menu")]]
  139.                 ))
  140.         else :
  141.             for ch in admins :
  142.                 print("#" + str(action) + " inoltro il messaggio a: " + str(ch))
  143.                 bot.forwardMessage(ch , chatid , msg["message_id"])
  144.             inqueque.remove(chatid)
  145.             sendAndLog(chatid , "Grazie del contributo, il tuo sfondo verrà presto analizzato dal nostro staff")
  146.             menu(chatid)
  147.         return
  148.  
  149.     if msginfo[0] != "text" :
  150.         sendAndLog(chatid , "Scusa, non credo di aver capito")
  151.         return
  152.  
  153.     if txt == "debug" :
  154.         debug(chatid)
  155.         return
  156.    
  157.     if txt == "start" :
  158.         menu(chatid)
  159.         return
  160.  
  161.     if txt == "sfondo del mese" :
  162.         request = requests.get(server + folder + "categories/month.json")
  163.         request.raise_for_status()
  164.         obj = json.loads(request.text)
  165.         if obj == {} :
  166.             sendAndLog(chatid , "Per ora non c'è uno sfondo del mese")
  167.         if len(list(obj.keys())) > 1 or len(list(obj.values())) > 1 :
  168.             raise Exception("JSON File Format Invalid")
  169.         ct = list(obj.keys())[0]
  170.         vl = list(obj.values())[0]
  171.         cts = getCategoriesList()
  172.         raw = cts[ct]
  173.         sendAndLog(chatid , "Ecco lo sfondo di questo mese:")
  174.         bot.sendPhoto(chatid , server + folder + "categories/" + raw + "/" + vl ,)
  175.         return
  176.    
  177.     if txt == "categorie" :
  178.         categories(chatid)
  179.         return
  180.  
  181.     if txt == "menu" :
  182.         if chatid in list(assocs.keys()) :
  183.             del assocs[chatid]
  184.         menu(chatid)
  185.         return
  186.  
  187.     if txt == "parla con me" :
  188.         sendAndLog(chatid , "Puoi contattarmi tramite @AxwellBot! Funziona anche per i limitati!" , reply_markup= \
  189.                    InlineKeyboardMarkup(inline_keyboard=[
  190.                        [InlineKeyboardButton(text="Vai al bot!" , url="http://t.me/AxwellBot")],
  191.                     ]))
  192.         return
  193.  
  194.     if txt == "mandaci il tuo sfondo preferito!" :
  195.         sendAndLog(chatid , "Invia il tuo sfondo come file, verrà inoltrato immediatamente agli staffer di sfondipaper!" , reply_markup=ReplyKeyboardMarkup(
  196.                     keyboard=[[KeyboardButton(text="Torna al menu")]]
  197.                 ))
  198.         inqueque.append(chatid)
  199.  
  200.     if txt in listLower(list(categoriesList.keys())) :
  201.         photos = getCategory(categoriesList[msg["text"]])
  202.         if photos == [] :
  203.                 sendAndLog(chatid , "This category has not images now")
  204.                 #menu(chatid)
  205.                 return
  206.         print(photos)
  207.         photo = random.choice(photos)
  208.         sendAndLog(chatid , "Ecco uno sfondo della categoria: " + msg["text"].replace("/",""))
  209.         bot.sendPhoto(chatid , server + folder + "categories/" + categoriesList[msg["text"]] + "/" + photo)
  210.         sendAndLog(chatid , "Attendi un po' mentre viene caricata la versione non compressa...")
  211.         sendImageNotCompressed(chatid , server + folder + "categories/" + categoriesList[msg["text"]] + "/" + photo)
  212.         sendAndLog(chatid , "Sfondo Caricato!" , reply_markup=ReplyKeyboardMarkup(keyboard=[
  213.             [KeyboardButton(text="Avanti")],
  214.             [KeyboardButton(text="Menu")]
  215.         ]))
  216.         assocs[chatid] = msg["text"]
  217.         return
  218.  
  219.     if txt == "avanti" :
  220.         if chatid in list(assocs.keys()) :
  221.             photos = getCategory(categoriesList[assocs[chatid]])
  222.             if photos == [] :
  223.                 print("This category has not images now")
  224.                 return
  225.             photo = random.choice(photos)
  226.             sendAndLog(chatid , "Ecco uno sfondo della categoria: " + assocs[chatid])
  227.             bot.sendPhoto(chatid , server + folder + "categories/" + categoriesList[assocs[chatid]] + "/" + photo)
  228.             sendAndLog(chatid , "Attendi un po' mentre viene caricata la versione non compressa...")
  229.             sendImageNotCompressed(chatid , server + folder + "categories/" + categoriesList[assocs[chatid]] + "/" + photo)
  230.             sendAndLog(chatid , "Sfondo Caricato!" , reply_markup=ReplyKeyboardMarkup(keyboard=[
  231.                 [KeyboardButton(text="Avanti")],
  232.                 [KeyboardButton(text="Menu")]
  233.             ]))
  234.         else :
  235.             print("Non hai selezionato nessuna categoria, per favore, usa solo la tastiera del bot e non la chat diretta")
  236.         return
  237.    
  238.    
  239.     return
  240.  
  241. print("Listening...")
  242. bot = telepot.Bot(token)
  243. bot.message_loop(handle)
  244.  
  245. try :
  246.     while True :
  247.         time.sleep(1)
  248. except :
  249.     del bot
  250.     del handle
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement