Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import telepot , random , pprint , requests , json , random , os , sys , time
- from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup , InlineKeyboardButton
- token = "XXXXXX"
- bot = None
- msginfo = None
- action = None
- message = None
- admins = [212546200 , 144218415]
- assocs = {}
- inqueque = []
- server = "http://sfondipaper.altervista.org"
- folder = "/"
- def debug(chatid) :
- sendImageNotCompressed(chatid , "http://www.sfondipaper.altervista.org/categories/os/test.png")
- return
- def sendImageNotCompressed(chatid , url) :
- checkWorkDir()
- request = requests.get(url)
- request.raise_for_status()
- with open("." + os.sep + "work" + os.sep + os.path.basename(url) , "wb") as file :
- for chunk in request.iter_content(10000) :
- file.write(chunk)
- with open("." + os.sep + "work" + os.sep + os.path.basename(url) , "rb") as file :
- bot.sendDocument(chatid , file)
- return
- def checkWorkDir() :
- os.makedirs("work" , exist_ok=True)
- def menu(chatid) :
- sended = sendAndLog(chatid , "Benvenuto, " + message["from"]["first_name"] + " questo è il bot di @sfondipaper!" ,
- reply_markup=ReplyKeyboardMarkup(
- keyboard=[
- [KeyboardButton(text="Categorie"),
- KeyboardButton(text="Parla con me"),],
- [KeyboardButton(text="Sfondo del mese"),
- KeyboardButton(text="Sfondo Pack zip")],
- [KeyboardButton(text="Mandaci il tuo sfondo preferito!")]
- ]
- ))
- def categories(chatid) :
- cat = getCategoriesList()
- names = list(cat.keys())
- for n in names :
- names[names.index(n)] = KeyboardButton(text=n)
- result = []
- while len(names) != 0 :
- result.append(names[:3])
- del names[:3]
- result.append([KeyboardButton(text="Menu")])
- sended = sendAndLog(chatid , "Scegli una categoria per vedere gli sfondi",
- reply_markup=ReplyKeyboardMarkup(
- keyboard=result
- )
- )
- def getCategoriesList() :
- request = requests.get(server + folder + "categories/categories.json")
- request.raise_for_status()
- txt = request.text
- obj = json.loads(txt)
- return obj
- def getCategory(category) :
- url = ""
- if category == "all" :
- url = "/all.json"
- else :
- url = "/" + category + "/list.json"
- request = requests.get(server + folder + "categories" + url)
- request.raise_for_status()
- text = request.text
- obj = json.loads(text)
- return obj
- def sendAndLog(chatid , \
- text, \
- parse_mode=None, \
- disable_web_page_preview=None, \
- disable_notification=None, \
- reply_to_message_id=None, \
- reply_markup=None) :
- global bot
- bot.sendMessage(chatid, \
- text, parse_mode=parse_mode, \
- disable_web_page_preview=disable_web_page_preview, \
- disable_notification=disable_notification, \
- reply_to_message_id=reply_to_message_id, \
- reply_markup=reply_markup)
- print("#" + str(action) + "\tRisposta: " + text)
- def listLower(l) :
- for i in l :
- l[l.index(i)] = i.lower()
- return l
- def handle(msg) :
- global bot
- global chatid
- global action
- global msginfo
- global message
- #pprint.pprint(msg)
- try :
- bot.getMe()
- except :
- sys.exit(0)
- action = random.randint(1,99999)
- msginfo = telepot.glance(msg)
- chatid = msginfo[2]
- message = msg
- categoriesList = getCategoriesList()
- if msginfo[0] == "text" :
- print("#" + str(action) + "\t" + str(chatid) + " scrive: " + msg["text"])
- txt = msg["text"].lower().replace("/","")
- else :
- print("#" + str(action) + "\t" + str(chatid) + " invia un dato")
- if chatid in inqueque :
- if not msginfo[0] == "document" :
- if txt == "torna al menu" :
- inqueque.remove(chatid)
- menu(chatid)
- else :
- sendAndLog(chatid , "Invia l'immagine in formato file" , reply_markup=ReplyKeyboardMarkup(
- [[KeyboardButton(text="Torna al menu")]]
- ))
- else :
- for ch in admins :
- print("#" + str(action) + " inoltro il messaggio a: " + str(ch))
- bot.forwardMessage(ch , chatid , msg["message_id"])
- inqueque.remove(chatid)
- sendAndLog(chatid , "Grazie del contributo, il tuo sfondo verrà presto analizzato dal nostro staff")
- menu(chatid)
- return
- if msginfo[0] != "text" :
- sendAndLog(chatid , "Scusa, non credo di aver capito")
- return
- if txt == "debug" :
- debug(chatid)
- return
- if txt == "start" :
- menu(chatid)
- return
- if txt == "sfondo del mese" :
- request = requests.get(server + folder + "categories/month.json")
- request.raise_for_status()
- obj = json.loads(request.text)
- if obj == {} :
- sendAndLog(chatid , "Per ora non c'è uno sfondo del mese")
- if len(list(obj.keys())) > 1 or len(list(obj.values())) > 1 :
- raise Exception("JSON File Format Invalid")
- ct = list(obj.keys())[0]
- vl = list(obj.values())[0]
- cts = getCategoriesList()
- raw = cts[ct]
- sendAndLog(chatid , "Ecco lo sfondo di questo mese:")
- bot.sendPhoto(chatid , server + folder + "categories/" + raw + "/" + vl ,)
- return
- if txt == "categorie" :
- categories(chatid)
- return
- if txt == "menu" :
- if chatid in list(assocs.keys()) :
- del assocs[chatid]
- menu(chatid)
- return
- if txt == "parla con me" :
- sendAndLog(chatid , "Puoi contattarmi tramite @AxwellBot! Funziona anche per i limitati!" , reply_markup= \
- InlineKeyboardMarkup(inline_keyboard=[
- [InlineKeyboardButton(text="Vai al bot!" , url="http://t.me/AxwellBot")],
- ]))
- return
- if txt == "mandaci il tuo sfondo preferito!" :
- sendAndLog(chatid , "Invia il tuo sfondo come file, verrà inoltrato immediatamente agli staffer di sfondipaper!" , reply_markup=ReplyKeyboardMarkup(
- keyboard=[[KeyboardButton(text="Torna al menu")]]
- ))
- inqueque.append(chatid)
- if txt in listLower(list(categoriesList.keys())) :
- photos = getCategory(categoriesList[msg["text"]])
- if photos == [] :
- sendAndLog(chatid , "This category has not images now")
- #menu(chatid)
- return
- print(photos)
- photo = random.choice(photos)
- sendAndLog(chatid , "Ecco uno sfondo della categoria: " + msg["text"].replace("/",""))
- bot.sendPhoto(chatid , server + folder + "categories/" + categoriesList[msg["text"]] + "/" + photo)
- sendAndLog(chatid , "Attendi un po' mentre viene caricata la versione non compressa...")
- sendImageNotCompressed(chatid , server + folder + "categories/" + categoriesList[msg["text"]] + "/" + photo)
- sendAndLog(chatid , "Sfondo Caricato!" , reply_markup=ReplyKeyboardMarkup(keyboard=[
- [KeyboardButton(text="Avanti")],
- [KeyboardButton(text="Menu")]
- ]))
- assocs[chatid] = msg["text"]
- return
- if txt == "avanti" :
- if chatid in list(assocs.keys()) :
- photos = getCategory(categoriesList[assocs[chatid]])
- if photos == [] :
- print("This category has not images now")
- return
- photo = random.choice(photos)
- sendAndLog(chatid , "Ecco uno sfondo della categoria: " + assocs[chatid])
- bot.sendPhoto(chatid , server + folder + "categories/" + categoriesList[assocs[chatid]] + "/" + photo)
- sendAndLog(chatid , "Attendi un po' mentre viene caricata la versione non compressa...")
- sendImageNotCompressed(chatid , server + folder + "categories/" + categoriesList[assocs[chatid]] + "/" + photo)
- sendAndLog(chatid , "Sfondo Caricato!" , reply_markup=ReplyKeyboardMarkup(keyboard=[
- [KeyboardButton(text="Avanti")],
- [KeyboardButton(text="Menu")]
- ]))
- else :
- print("Non hai selezionato nessuna categoria, per favore, usa solo la tastiera del bot e non la chat diretta")
- return
- return
- print("Listening...")
- bot = telepot.Bot(token)
- bot.message_loop(handle)
- try :
- while True :
- time.sleep(1)
- except :
- del bot
- del handle
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement