def list_active_torrents(n, chat, message, callback) -> None: torrents = qbittorrent_control.get_torrent_info() if not torrents: btn = botogram.Buttons() btn[0].callback("🔙 Menu", "menu") try: message.edit("There are no torrents", attach=btn) except botogram.api.APIError: chat.send("There are no torrents", attach=btn) return btn = botogram.Buttons() if n == 1: for key, i in enumerate(torrents): btn[key].callback(i.name, callback, str(key)) btn[key + 1].callback("🔙 Menu", "menu") try: message.edit_attach(btn) except botogram.api.APIError: chat.send("Qbitorrent Control", attach=btn) else: for key, i in enumerate(torrents): btn[key].callback(i.name, "torrentInfo", str(key)) btn[key + 1].callback("🔙 Menu", "menu") try: message.edit_attach(btn) except botogram.api.APIError: chat.send("Qbitorrent Control", attach=btn)
def process_message(chat, message): # "return True" blocca l'esecuzione di ulteriori funzioni da parte di botogram if db.get_user_setting(message.sender.id, 'status') == 'adding_channel': if isinstance(message.forward_from, botogram.objects.chats.Chat): if message.forward_from.type == 'channel': channel = message.forward_from user = message.sender btns = botogram.Buttons() if not db.get_channel(channel.id): # provo a mandare un messaggio nel canale, se lo manda # il bot è admin, altrimenti non lo è e chiede di riprovare try: msg = bot.chat(channel.id).send('p') msg.delete( ) # cancello le tracce del messaggio inviato except botogram.api.APIError: btns[0].callback(_('msg.cancel_operation_button'), "cancel_operation_callback") chat.send(_('msg.bot_not_in_channel', title=channel.title), attach=btns) return True # qui il canale viene aggiunto con successo db.set_user_setting(user.id, 'status', '') db.add_channel(channel.id, user.id) btns[0].callback(_('msg.configure_channel_button'), "configure_channel_callback", str(channel.id)) chat.send(_('msg.channel_added', title=channel.title), attach=btns) return True else: # il canale è già registrato e non può essere aggiunto di nuovo db.set_user_setting(user.id, 'status', '') chat.send( _('msg.channel_already_added', title=channel.title)) return True else: # il messaggio inoltrato è di una chat privata o di un gruppo btns = botogram.Buttons() btns[0].callback(_('msg.cancel_operation_button'), "cancel_operation_callback") chat.send(_('msg.wrong_forward_type'), attach=btns) return True return False
def BackAdmintoAllmenua(query, message, chat): admins = [] if str(query.sender.id) in admins: btns = botogram.Buttons() btns[1].callback("MenuAdmin", "menuAdmin") btns[1].callback("Menu", "Menuutenti") btns[0].callback("delete", "delta") message.edit("Benvenuto " + str(query.sender.name) + " accesso come admin", attach=btns) else: btns = botogram.Buttons() btns[1].callback("Menu", "Menuutenti") message.edit("Benvenuto " + str(query.sender.name), attach=btns)
def posta(query, chat, message): message.photo.save(message.photo.file_id + ".png") btns = botogram.Buttons() btns[0].callback("✔️", "conferma") d = open("arrivo.txt", "r") f = d.readline() f = int(f) d.close() aggiunta = f + 1 bot.chat(-1005).set_description("ci sono " + str(aggiunta) + " memi ") g = open("arrivo.txt", "w") k = g.write(str(aggiunta)) new = "random" + str(aggiunta) + ".jpg" os.rename(str(message.photo.file_id) + ".png", new) g.close() message.delete() x = open("tags.txt", "r") f = x.readline() x.close() insta = Bot() insta.login(username="", password="") insta.upload_photo(new, caption=f) try: os.rename(new + ".REMOVE_ME", new) #save the file bot.chat(message.caption).send( "il tuo meme è stato postato grazie per l'aiuto") md5 = hashlib.md5() with open(new, "rb") as thefile: buf = thefile.read() md5.update(buf) x = open("database.txt", "a") f = x.write(str(md5.hexdigest()) + "\n") x.close() except: bot.chat(-100).send("il formato dell'immagine non è adatto")
def groupvote(chat, message, data, query): '''the request will be voted in the group''' d.execute("SELECT stage FROM request WHERE userid=?", (int(data), )) x = d.fetchone() try: if x[0] == 4: try: bot.chat(int(data)).send(p["vote"]) except botogram.ChatUnavailableError as e: message.delete() if e == "blocked": chat.send("The user has blocked the Bot. Request canceled") elif e == "account_deleted": chat.send("The user deleted its account. Request canceled") else: chat.send("User unavailable: %s" % (e)) d.execute("DELETE FROM request WHERE userid=?", (int(data), )) dat.commit() else: message.edit("Already in another Stage baby") except TypeError: dat.rollback() message.edit(p["alreadydel"]) else: d.execute('UPDATE request SET stage=5 WHERE userid=?', (int(data), )) dat.commit() message.edit( verdict(int(data), 'vote', query.sender.name, query.sender.id)) d.execute("SELECT id FROM ids WHERE type=3") groups = d.fetchone() bt = botogram.Buttons() bt[0].callback('start', 'startpoll', data) for group in groups: bot.chat(group).send("New Poll by %s" % (data), attach=bt)
def paid_callback(query, chat, message): user = users.find_one(filter={'chat_id': chat.id}, projection={ '_id': 0, 'username': 1, 'this_month': 1 }) if user.get('this_month'): msg = """ you already paid for this month, bia pv reval konim. """ chat.send(msg) return msg = """ گاد بلس یو!, waiting for admin approval ... """ chat.send(msg) btns = botogram.Buttons() btns[0].callback("confirm", "paid_confirm") username = user.get("username").replace("_", "\\_") send_msg_to_admin(f'{username} just paid', btns)
def first(message, chat): """Do your request""" if chat.type == "private": if checkreq(chat, 'request') is True: bt = botogram.Buttons() bt[0].callback("Cancel", "zero") chat.send("Send me the name of your $request", attach=bt)
def circuitslist_command(chat, args): """<season> List the circuits If the season is not specified or the year is wrong the current season will be used""" if len(args) > 0: season = control_year(args[0]) else: season = "current" url = "https://ergast.com/api/f1/{}/circuits.json".format(season) r = requests.get(url) data = r.json()['MRData']['CircuitTable']['Circuits'] btns = botogram.Buttons() i = -1 y = 0 for dat in data: btns[y].callback(dat['circuitName'], "circuitslst", dat['circuitId'] + "#{}".format(season)) if i % 2 == 0: y += 1 i += 1 chat.send("Circuit list\n*Season: *{}".format(season), attach=btns)
def qualyslast(message): url = "http://ergast.com/api/f1/current/last/qualifying.json" r = requests.get(url) data = r.json()['MRData']['RaceTable']['Races'][0]['QualifyingResults'] btns = botogram.Buttons() btns[0].callback("Race", "racelast") btns[1].callback("Go back", "menulast") text = "DRIVER | Time\n\n" for driver in data: try: if driver['Q3'] != "": text += driver['Driver']['code'] + " | " + \ driver['Q3'] + "\n" else: text += driver['Driver']['code'] + " | DNF\n" except KeyError: try: if driver['Q2'] != "": text += driver['Driver']['code'] + " | " + \ driver['Q2'] + "\n" else: text += driver['Driver']['code'] + " | DNF\n" except KeyError: if driver['Q1'] != "": text += driver['Driver']['code'] + " | " + \ driver['Q1'] + "\n" else: text += driver['Driver']['code'] + " | DNF\n" message.edit(text, attach=btns)
def constructorlist(message, data): data, season = data.split("#") url = "http://ergast.com/api/f1/{}/constructors.json".format(season) btns = botogram.Buttons() r = requests.get(url) dat = r.json()['MRData']['ConstructorTable']['Constructors'] text = "" for driver in dat: if driver['constructorId'] == data: btns[0].url(driver['name'], driver['url']) vincite = requests.get("https://ergast.com/api/f1/constructors/" + data + "/constructorStandings/1/seasons.json") vittorie = vincite.json()['MRData'] l2 = "" for c in vittorie['SeasonTable']['Seasons']: l2 += c['season'] + " , " text += ("*" + driver['name'] + "*\n\n*Championships: *" + vittorie['total'] + "\n*Years: *" + l2[0:len(l2) - 3] + "\n*Nationality: *" + driver['nationality']) btns[1].callback("Go back", "menudconstructors", season) message.edit(text, attach=btns)
def raceresults_command(chat, args): """<season> List all f1 races and get all results If the season is not specified or the year is wrong the current season will be used""" if len(args) > 0: season = control_year(args[0]) else: season = "current" url = "https://ergast.com/api/f1/{}/results.json?limit=99999".format( season) r = requests.get(url) data_requests = r.json()['MRData']['RaceTable']['Races'] btns = botogram.Buttons() i = -1 y = 0 for dat in data_requests: btns[y].callback(dat['raceName'], "raceresult", dat['round'] + "#{}".format(season)) if i % 2 == 0: y += 1 i += 1 chat.send("Race results\n*Season: *{}".format(season), attach=btns, syntax="markdown")
def first(message, chat): """Make Your Request!""" if chat.type == "private": if checkreq(chat, 'request'): bt = botogram.Buttons() bt[0].callback(p["request"][0], "zero", str(chat.id)) chat.send(p["request"][1], attach=bt)
def driverlist(message, data): data, season = data.split("#") btns = botogram.Buttons() url = "http://ergast.com/api/f1/{}/drivers.json".format(season) r = requests.get(url) data_requests = r.json()['MRData']['DriverTable']['Drivers'] text = "" for driver in data_requests: if driver['driverId'] == data: btns[0].url(driver['givenName'] + " " + driver['familyName'], driver['url']) text += ("*" + driver['givenName'] + " " + driver['familyName'] + "*\n\n*Number: *" + driver['permanentNumber'] + "\n" + "*Date of birth: *" + convert_data(driver['dateOfBirth']) + "\n*Nationality: *" + driver['nationality']) btns[1].callback("Go back", "menudrivers", season) message.edit(text, attach=btns)
def refreshpin(chat, message): if message.sender in chat.admins: if chat.type == 'supergroup': d.execute("SELECT mesid, name FROM request WHERE stage=5") reqs = d.fetchall() bt = botogram.Buttons() for n, x in enumerate(reqs): lnk = "t.me/" + chat.username + "/" + str(x[0]) bt[n].url(x[1], lnk) if message.sender.id != bot.itself.id: try: additional_text = "\n\n_%s_\n\n" % ( message.reply_to_message.text) except AttributeError: additional_text = "\n" tosend = (p['refreshpin'] % (additional_text)) chat.send(tosend, attach=bt, syntax="markdown", preview=False) bot.api.call("pinChatMessage", { "chat_id": chat.id, "message_id": (message.id + 1) }) r.set('pinned', message.id + 1) else: additional_text = "\n" tosend = p['refreshpin'] % (additional_text) mex = r.get('pinned') bot.edit_message(chat.id, mex, tosend, attach=bt, syntax="markdown", preview=False)
def torrent_info_callback(message, data) -> None: torrent = qbittorrent_control.get_torrent_info(data=int(data)) progress = torrent.progress * 100 text = "" if progress == 0: text += f"{torrent.name}\n[ ] " \ f"{round(progress, 2)}% completed\n" \ f"State: {torrent.state.capitalize()}\n" \ f"Download Speed: {convert_size(torrent.dlspeed)}/s\n" \ f"Size: {convert_size(torrent.size)}\nETA: " \ f"{convert_eta(int(torrent.eta))}\n\n" elif progress == 100: text += f"{torrent.name}\n[completed] " \ f"{round(progress, 2)}% completed\n" \ f"State: {torrent.state.capitalize()}\n" \ f"Upload Speed: {convert_size(torrent.upspeed)}/s\n\n" else: text += f"{torrent.name}\n[{'=' * int(progress / 10)}" \ f"{' ' * int(12 - (progress / 10))}]" \ f" {round(progress, 2)}% completed\n" \ f"State: {torrent.state.capitalize()} \n" \ f"Download Speed: {convert_size(torrent.dlspeed)}/s\n" \ f"Size: {convert_size(torrent.size)}\nETA: " \ f"{convert_eta(int(torrent.eta))}\n\n" btn = botogram.Buttons() btn[0].callback("⏸ Pause", "pause", data) btn[0].callback("▶️ Resume", "resume", data) btn[1].callback("🗑 Delete", "delete_one", data) btn[2].callback("🔙 Menu", "menu") message.edit(text, attach=btn)
def category(chat, message, data, query, shared) -> None: btn = botogram.Buttons() categories = qbittorrent_control.get_categories() if categories is None: if "magnet" in data: addmagnet_callback(shared, query, "#None") else: addtorrent_callback(shared, query, "#None") return key = 0 for key, i in enumerate(categories): btn[key].callback(i, data, i) btn[key + 1].callback("None", data, "None") btn[key + 2].callback("🔙 Menu", "menu") try: message.edit("Choice a category:", attach=btn) except Exception: chat.send("Choice a category:", attach=btn)
def modify_category_callback(chat, message, data, shared): btn = botogram.Buttons() if data is not None: btn[2].callback("🔙 Menu", "menu") shared['status'] = f"category_dir_modify#{data}" message.edit(f"Send new path for category {data}", attach=btn) return categories = qbittorrent_control.get_categories() if categories is None: btn[0].callback("🔙 Menu", "menu") message.edit("There are no categories", attach=btn) return key = 0 for key, i in enumerate(categories): btn[key].callback(i, "modify_category", i) btn[key + 1].callback("🔙 Menu", "menu") try: message.edit("Choice a category:", attach=btn) except Exception: chat.send("Choice a category:", attach=btn)
def remove_category_callback(chat, message, data): btn = botogram.Buttons() if data is not None: qbittorrent_control.remove_category(data=data) btn[0].callback("🔙 Menu", "menu") message.edit(f"The category {data} has been removed", attach=btn) return categories = qbittorrent_control.get_categories() if categories is None: btn[0].callback("🔙 Menu", "menu") message.edit("There are no categories", attach=btn) return key = 0 for key, i in enumerate(categories): btn[key].callback(i, "remove_category", i) btn[key + 1].callback("🔙 Menu", "menu") try: message.edit("Choice a category:", attach=btn) except Exception: chat.send("Choice a category:", attach=btn)
def drivers_command(chat, args): """list F1 drivers""" if len(args) > 0: season = control_year(args[0]) else: season = "current" url = "http://ergast.com/api/f1/{}/drivers.json".format(season) btns = botogram.Buttons() r = requests.get(url) data = r.json()['MRData']['DriverTable']['Drivers'] i = 1 y = 0 for driver in data: btns[y].callback(driver['familyName'], "drivers", driver['driverId'] + "#{}".format(season)) if i % 3 == 0: y += 1 i += 1 chat.send("Drivers\n*Season: *{}".format(season), attach=btns)
def good(chat, message, data, query): '''Accept the request without voting procedure''' d.execute("SELECT stage FROM request WHERE userid=?", (int(data), )) try: stage = int(d.fetchone()[0]) if stage <= 5: d.execute('UPDATE request SET stage=6 WHERE userid=?', (int(data), )) dat.commit() bt = botogram.Buttons() bt[0].callback(p["good"][1], 'zero2', str(data)) if stage == 4: message.edit( verdict(int(data), True, query.sender.name, query.sender.id)) try: bot.chat(int(data)).send(p["good"][0]) except botogram.ChatUnavailableError as e: message.delete() chat.send("User unavailable: %s" % (e)) d.execute("DELETE FROM request WHERE userid=?", (int(data), )) dat.commit() else: logch.send(staffvis(data), attach=bt) else: logch.send(staffvis(data), attach=bt) else: message.edit("Already in another Stage baby") except TypeError: dat.rollback() message.edit(p["alreadydel"])
def constructors_command(chat, args): """<season> List F1 constructors If the season is not specified or the year is wrong the current season will be used""" if len(args) > 0: season = control_year(args[0]) else: season = "current" url = "http://ergast.com/api/f1/{}/constructors.json".format(season) btns = botogram.Buttons() r = requests.get(url) data = r.json()['MRData']['ConstructorTable']['Constructors'] i = 1 y = 0 for driver in data: btns[y].callback(driver['name'], "constructorlst", driver['constructorId'] + "#{}".format(season)) if i % 2 == 0: y += 1 i += 1 chat.send("Constructors list\n*Season: *{}".format(season), attach=btns)
def callback_grafico_nazionale_cumulativo(query, chat, message): btns = botogram.Buttons() btns[0].callback("Indietro", "callback_grafici_nazionali", "delete") #covid.create_grafico_cumulativo_nazionale() # non posso aggiungere una foto ad un messaggio esistente quindi lo elimino message.delete() chat.send_photo("grafici/nazionali/cumulativo.png", attach=btns)
def raceresultquery(message, data): data, season = data.split("#") url = "https://ergast.com/api/f1/{}/{}/results.json".format( season, str(data)) r = requests.get(url) data_requests = r.json()['MRData']['RaceTable']['Races'][0]['Results'] btns = botogram.Buttons() btns[0].callback("Qualify", "qualyresult", str(data) + "#{}".format(season)) btns[1].callback("Go back", "menuresults", season) text = "*{}*\n\nDRIVER | GAP\n".format( r.json()['MRData']['RaceTable']['Races'][0]['raceName']) for driver in data_requests: try: text += driver['Driver']['code'] + " | " + \ driver['Time']['time'] + "\n" except KeyError: try: text += driver['Driver']['code'] + " | " + \ driver['status'] + "\n" except Exception: pass message.edit(text, attach=btns)
def start_command(chat, message, args): """Start the bot""" conn = sqlite3.connect('users.db') c = conn.cursor() try: c.execute("SELECT user_id FROM users WHERE user_id = ?", (message.sender.id, )) except sqlite3.OperationalError: return lang(chat, message) data = c.fetchall() if not data: conn.close() return lang(chat, message) else: _ = getlang(message.sender.id) btns = botogram.Buttons() btns[0].url(_("Open a pull request"), "https://github.com/Bestfast/wednesday-nhentai-bot/pulls") btns[1].url(_("Enter in the official bot's group"), "https://t.me/joinchat/Fb98J0njHKRnhj3LvF0m6A") btns[2].url(_("Contact the delevoper"), "https://t.me/Bestfast") chat.send(_( "Hi! This bot is in development. if you want to help, you can open a pull request in the GitHub's repo." ), attach=btns)
def circuitsinfo(message, data): data, season = data.split("#") url = "https://ergast.com/api/f1/{}/circuits/{}.json".format( season, str(data)) url2 = "https://ergast.com/api/f1/{}/circuits/{}/races.json".format( season, str(data)) r = requests.get(url) r2 = requests.get(url2) dat = r.json()['MRData']['CircuitTable']['Circuits'][0] dat2 = r2.json()['MRData']['RaceTable']['Races'][0] btns = botogram.Buttons() btns[0].url(dat['circuitName'], dat['url']) btns[1].callback("Send Position", "sendCircuitPosition", data + "#{}".format(season)) btns[2].callback("Go back", "menuCircuits", season) text = ("*{}*\n*Round:* {}\n*Date:* {}" "\n*Time:* {}\n*Locality:* {}, {}").format( dat['circuitName'], dat2['round'], convert_data(dat2['date']), convert_time(dat2['time']), dat['Location']['locality'], dat['Location']['country']) message.edit(text, attach=btns, syntax="markdown")
def sondaggioo(chat, message, args, bot): admins = [""] if str(message.sender.id) in admins: ar = " ".join(args) btns = botogram.Buttons() btns[0].callback("sì", "sondaggiosi") btns[1].callback("no", "sondaggioNo") ida = 0 num_lines = sum(1 for line in open('log-in.txt')) inviati_a = " " while num_lines > ida: open_file = open('log-in.txt', 'r') file_lines = open_file.readlines() file = file_lines[ida].strip() # First Line if file is None: pass if int(file) < 0: pass else: try: bot.chat(file).send(ar, attach=btns) x = open("sondaggioid.txt", "w") x.write(str(message.id)) x.close() inviati_a = inviati_a + " " + file except botogram.ChatUnavailableError as e: bot.chat(-1000).send("Can't send messages to %s (reason: %s)" % (e.chat_id, e.reason)) ida = ida + 1 bot.chat(-100).send("il sondaggio è stato inviato a " + str(inviati_a) + "\nil testo è " + str(ar) + "\ndall admin @" + str(message.sender.username))
def month_passed(chat, message): """ This one is mine :))) Don't even think about using it! """ msg = """ سلام بچهها. هزینهی این ماهمون میشه نفری{} شماره کارت: {} هر وقت ریختید، این دکمهی پایین رو بزنید. اگه اسکرین شات یا چیزی خواستید بفرستید، برا خودم بفرستید. این باته نمیفهمه عکسو :)) """.format(re.sub(month_passed_command, '', message.text), config("credit_card")) btns = botogram.Buttons() btns[0].callback("rikhtam, boro halesho bebar", "paid") users.update_many({}, { "$set": { "this_month": False }, "$inc": { "months": -1 } }) users.update_many({"months": {"$gte": 0}}, {"$set": {"this_month": True}}) send_msg_to_not_paid_users(msg, btns)
def helpaddgroup(query, message, chat): mex = message.reply_to_message btns = botogram.Buttons() btns[0].callback("Go Back", "Backgiorno") message.edit( "spiegazione: aggiungi il bot per i memi giornalieri (gruppi)", attach=btns)
def hello_command(chat, message, args): """Welcome to Telegram File System """ btns = botogram.Buttons() # btns[0].callback("Prenota un appuntamento", "prenota") # chat.send("Benvenuto al Pei - chat.id: " + str(chat.id), attach=btns) chat.send("chat_id: " + str(chat.id))
def helpnotifiche(query, chat, message): mex = message.reply_to_message btns = botogram.Buttons() btns[0].callback("Go Back", "Backgiorno") message.edit( "spiegazione: iscriviti alle immagini giornalieri (persone singole)", attach=btns)