def sauce(update: Update, context: CallbackContext ): results = " " API = '1ee746dd98d9d3f2b6f366236cb35630d270cd90' sauce = SauceNao(api_key=API, db = 999, numres = 6) bot = context.bot msg = update.effective_message msg_id = update.effective_message.message_id chat = update.effective_chat reply = msg.reply_to_message filename_photo = "saucey.png" filename_gif = "saucey.gif" if not reply: msg.reply_text("Reply to something baka...") return photo = "False" gif = "False" m = msg.reply_text("Where is my frying pan.. Ahh!! Hot Sauce-ing now!!", reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text = "(^_-)", callback_data = "Nah")]])) if reply: if reply.photo: photo_id = reply.photo[-1].file_id photo = "True" elif reply.animation: gif_id = reply.animation.file_id gif = "True" elif reply.video: if reply.video.file_size >= 5: gif_id = reply.video.file_id gif = "True" else: m.edit_text("Ahh That is too big for setsuna, give a small sized one Nya!!") elif reply.sticker: photo_id = reply.sticker.file_id photo = "True" else: m.edit_text("Nyah!!, give a gif, photo or a sticker!! ") return if photo == "True": file = bot.get_file(photo_id) dl = file.download(filename_photo) oo = open(dl, 'rb') results = sauce.from_file(oo) os.remove(dl) elif gif == "True" : file = bot.get_file(gif_id) dl = file.download(filename_gif) nyah = cv2.VideoCapture(dl) heh, nyo = nyah.read() cv2.imwrite("nyah.png", nyo) results = sauce.from_file(open("nyah.png", 'rb')) nyah.release() os.remove(dl) #except Exception: #m.edit_text("Ahh its too big!!, Setsuna cant hanlde it Nya!") else: return ru = [] rsu_1 = int(results[0].index_id) rsu_2 = int(results[1].index_id) rsu_3 = int(results[2].index_id) rsu_4 = int(results[3].index_id) rsu_5 = int(results[4].index_id) rsu_6 = int(results[5].index_id) text = " " markup = " " tex_dan, url_dan, material_dan, creator_dan, source_dan, character_dan, tex_pix, mem_pix, url_pix, anime_url, anime_title, dan_simi, simi_pix, anime_year, anime_ep= " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " mal_url = "False" rsudan = "False" rsupix = "False" rsuAnime = "False" urgel = "False" if rsu_1 == 9: rsudan = "True" rsu = 0 elif rsu_2 == 9: rsudan = "True" rsu = 1 elif rsu_3 == 9: rsudan = "True" rsu = 2 elif rsu_4 == 9: rsudan = "True" rsu = 3 elif rsu_5 == 9: rsudan = "True" rsu = 4 elif rsu_6 == 9: rsudan = "True" rsu = 5 else: print("Danboruu not found") if rsu_1 == 5: rsupix = "True" rsu2 = 0 elif rsu_2 == 5: rsupix = "True" rsu2 = 1 elif rsu_3 == 5: rsupix = "True" rsu2 = 2 elif rsu_4 == 5: rsupix = "True" rsu2 = 3 elif rsu_5 == 5: rsupix = "True" rsu2 = 4 elif rsu_6 == 5: rsupix = "True" rsu2 = 5 else: print("Pixiv not found...") if rsu_1 == 21: rsuAnime = "True" rsu3 = 0 elif rsu_2 == 21: rsuAnime = "True" rsu3 = 1 elif rsu_3 == 21: rsuAnime = "True" rsu3 = 2 elif rsu_4 == 21: rsuAnime = "True" rsu3 = 3 elif rsu_5 == 21: rsuAnime = "True" rsu3 = 4 elif rsu_6 == 21: rsuAnime = "True" rsu3 = 5 else: print("Not found on Anime..") if rsudan == "True" : dan_simi = str(results[rsu].similarity) tex_dan = str(results[rsu].title) urdan = results[rsu].urls try: urgel = urdan[1] except IndexError: pass if len(urdan) >= 2: tit = urdan.pop() else: pass url_dan = " ".join(urdan) di = results[rsu].raw ik = di.get('data') if not ik == "None": creator_dan = ik.get('creator') material_dan = ik.get('material') source_dan = ik.get('source') character_dan = ik.get('characters') print("Danboruu retrieving successful...") else: print("Danboruu either not found or retrieving unsuccessful") if rsuAnime == "True": raww = results[rsu3].raw anime_url = results[rsu3].urls try: anime_url = anime_url[0] except IndexError: pass simi = str(results[rsu3].similarity) deta = raww.get('data') anime_title = deta.get('source') anime_ep = deta.get('part') anime_year = deta.get('year') anime_timestamp = deta.get('est_time' ) print("Anime retrieving successful...") heh = Jikan() kek = heh.search('anime', anime_title, page=1) if kek: mal_url = kek['results'][0]['url'] else: mal_url = "False" else: print("Anime not found or retrieving unsuccessful") if rsupix == "True" : url_pix = " ".join(results[rsu2].urls) simi_pix = str(results[rsu2].similarity) tex_pix = str(results[rsu2].title) kek = results[rsu2].raw ti = kek.get('data') if not ti == 'None': mem_pix = ti.get('member_name') pixiv = "True" print("Pixiv retrieving successful...") else: print("Pixiv not found or retrieving unsuccessful") if rsuAnime == "True": text += f"*Title: {anime_title}\nEpisode: {anime_ep}* \n*Year Released*: `{anime_year}` \n*Timestamp:* `{anime_timestamp}`\n*Similarity:* `{simi}`" print(text) if rsudan == "True" : text += "*Title:*" + " " + f"*{tex_dan}*" + " " + "\n*Creator:*" + " " + f"*{creator_dan}*" + "\n*Material:*" + " " + f" *{material_dan}*" + "\n*Character:*" + " " + f"*{character_dan}*" + "\n" + "*Similarity: " + " " + f"{dan_simi}*" print(text) if rsupix == "True": if rsuAnime == "True": pass elif rsudan == "True": pass else: text += "*Title:*" + " " + f"*{tex_pix}*" + "\n" + "*Artist:*" + " " + f"*{mem_pix}*\n" + f"*Similarity: {simi_pix}*" if text == " ": text = "Sorry Not found!!, Setsuna sad... reeeee" #buttons made here keybo = [] if rsupix == "True": keybo.append([InlineKeyboardButton(text = "Pixiv", url = url_pix)]) if rsudan == "True": if not urgel == "False": keybo.append([InlineKeyboardButton(text = "Danboruu", url = url_dan), InlineKeyboardButton(text = "Gelbooru", url = urgel)]) elif url_dan == "False": if not urgel == "False": keybo.append([InlineKeyboardButton(text ="Gelbooru", url = urlgel)]) else: keybo.append([InlineKeyboardButton (text = "Danboruu", url = url_dan)]) if rsuAnime == "True": keybo.append([InlineKeyboardButton(text = "Anime-db", url = anime_url)]) if not mal_url == "False": keybo.append([InlineKeyboardButton(text = "MAL", url = mal_url)]) if len(keybo) >= 1: markup = InlineKeyboardMarkup(keybo) m.delete() msg.reply_text(text = text, reply_markup = markup, parse_mode = ParseMode.MARKDOWN) else: m.delete() msg.reply_text(text, parse_mode = ParseMode.MARKDOWN)
def Link(link, chat_id, quality, message_id): global spo global del1 del1 += 1 done = 0 quali = quality.split("MP3_")[-1] link = link.split("?")[0] ids = link.split("/")[-1] try: if "track/" in link: if "spotify" in link: try: url = spo.track(link) except Exception as a: if not "The access token expired" in str(a): sendMessage(chat_id, "Invalid link %s ;)" % link, reply_to_message_id=message_id) delete(chat_id) return spo = Spotify(generate_token()) url = spo.track(link) try: image1 = url['album']['images'][0]['url'] except IndexError: image1 = song_default_image name = url['name'] artist = url['album']['artists'][0]['name'] album = url['album']['name'] date = url['album']['release_date'] elif "deezer" in link: kind = "track" api_link = api_track % ids try: url = reque(api_link, chat_id, True).json() except AttributeError: delete(chat_id) return image1 = check_image(url['album']['cover_xl'], ids, kind) name = url['title'] artist = url['artist']['name'] album = url['album']['title'] date = url['album']['release_date'] if any(a in link for a in services_supported): sendPhoto(chat_id, image1, caption=(send_image_track_query % (name, artist, album, date))) track(link, chat_id, quality) else: sendMessage(chat_id, not_supported_links % link) elif "album/" in link: links = [] count = [0] if "spotify" in link: try: tracks = spo.album(link) except Exception as a: if not "The access token expired" in str(a): sendMessage(chat_id, "Invalid link %s ;)" % link, reply_to_message_id=message_id) delete(chat_id) return spo = Spotify(generate_token()) tracks = spo.album(link) try: image3 = tracks['images'][2]['url'] image1 = tracks['images'][0]['url'] except IndexError: image3 = image_resize(song_default_image, 90) image1 = song_default_image name = tracks['name'] artist = tracks['artists'][0]['name'] date = tracks['release_date'] tot = tracks['total_tracks'] def lazy(a): count[0] += a['duration_ms'] links.append(a['external_urls']['spotify']) for a in tracks['tracks']['items']: lazy(a) tracks = tracks['tracks'] for a in range(tot // 50 - 1): try: tracks = spo.next(tracks) except: spo = Spotify(generate_token()) tracks = spo.next(tracks) for a in tracks['items']: lazy(a) count[0] //= 1000 mode = downloa.download_albumspo elif "deezer" in link: api_link = api_album % ids kind = "album" try: url = reque(api_link, chat_id, True).json() except AttributeError: delete(chat_id) return count[0] = url['duration'] image1 = check_image(url['cover_xl'], ids, kind) image3 = image_resize(image1, 90) tot = url['nb_tracks'] links = [a['link'] for a in url['tracks']['data']] name = url['title'] artist = url['artist']['name'] date = url['release_date'] mode = downloa.download_albumdee if any(a in link for a in services_supported): if count[0] > seconds_limits_album: sendMessage( chat_id, "If you do this again I will come to your home and I will ddos your ass :)" ) delete(chat_id) return message_id = sendPhoto( chat_id, image1, caption=(send_image_album_query % (name, artist, date, tot)))['message_id'] conn = connect(db_file) c = conn.cursor() exists = [] for a in links: ids = a.split("/")[-1] lins = "track/%s" % ids exist = c.execute(where_query.format(lins, quali)).fetchone() if exist: exists.append(exist) if len(exists) < len(links) // 3: z = mode(link, quality=quality, recursive_quality=True, recursive_download=True, not_interface=not_interface) image3 = get_image(image3) for a in range(len(z)): sendAudio(chat_id, z[a], links[a], image3) else: for a in links: track(a, chat_id, quality) done = 1 else: sendMessage(chat_id, not_supported_links % link) elif "playlist/" in link: links = [] if "spotify" in link: musi = link.split("/") try: tracks = spo.user_playlist(musi[-3], musi[-1]) except Exception as a: if not "The access token expired" in str(a): sendMessage(chat_id, "Invalid link ;)", reply_to_message_id=message_id) delete(chat_id) return spo = Spotify(generate_token()) tracks = spo.user_playlist(musi[-3], musi[-1]) try: image1 = tracks['images'][0]['url'] except IndexError: image1 = song_default_image def lazy(a): try: links.append(a['track']['external_urls']['spotify']) except (KeyError, TypeError): links.append("Error :(") for a in tracks['tracks']['items']: lazy(a) added = tracks['tracks']['items'][0]['added_at'] owner = tracks['owner']['display_name'] tot = tracks['tracks']['total'] tracks = tracks['tracks'] for a in range(tot // 100 - 1): try: tracks = spo.next(tracks) except: spo = Spotify(generate_token()) tracks = spo.next(tracks) for a in tracks['items']: lazy(a) elif "deezer" in link: api_link = api_playlist % ids try: url = reque(api_link, chat_id, True).json() except AttributeError: delete(chat_id) return links = [a['link'] for a in url['tracks']['data']] image1 = url['picture_xl'] tot = url['nb_tracks'] added = url['creation_date'] owner = url['creator']['name'] if any(a in link for a in services_supported): if tot > max_songs: sendMessage(chat_id, "F**k you") delete(chat_id) return sendPhoto(chat_id, image1, caption=(send_image_playlist_query % (added, owner, tot))) for a in links: if a.startswith("http"): try: track(a, chat_id, quality) except: sendMessage(chat_id, "Cannot download %s:(" % a) else: sendMessage(chat_id, a) done = 1 else: sendMessage(chat_id, not_supported_links % link) elif "artist/" in link: if "deezer" in link: api_link = api_artist % ids try: url = reque(api_link, chat_id, True).json() except AttributeError: delete(chat_id) return keyboard = [[ InlineKeyboardButton( queries['top']['text'], callback_data=queries['top']['query'] % api_link), InlineKeyboardButton( queries['albums']['text'], callback_data=queries['albums']['query'] % api_link) ], [ InlineKeyboardButton( queries['radio']['text'], callback_data=queries['radio']['query'] % api_link), InlineKeyboardButton( queries['related']['text'], callback_data=queries['related']['query'] % api_link) ]] image1 = url['picture_xl'] artist = url['name'] albums = url['nb_album'] fans = url['nb_fan'] if any(a in link for a in services_supported[1:]): sendPhoto(chat_id, image1, caption=(send_image_artist_query % (artist, albums, fans)), reply_markup=InlineKeyboardMarkup(keyboard)) else: sendMessage(chat_id, not_supported_links % link) else: sendMessage(chat_id, not_supported_links % link) except FileNotFoundError: sendMessage(chat_id, "Resend link please...", reply_to_message_id=message_id) except error.TimedOut: sendMessage(chat_id, "Retry after a few minutes") except exceptions.QuotaExceeded: sendMessage(chat_id, "Please send the link %s again :(" % link) except exceptions.AlbumNotFound: sendMessage(chat_id, "Album %s didn't find on Deezer :(" % link) sendMessage( chat_id, "Try to search it throught inline mode or search the link on Deezer" ) except Exception as a: logging.error(a) logging.error(quality) logging.error(link) sendMessage( chat_id, "OPS :( Something went wrong please send to @An0nimia this link: {} {}, if this happens again" .format(link, quality)) if done == 1: sendMessage(chat_id, end_message, reply_to_message_id=message_id, reply_markup=InlineKeyboardMarkup(end_keyboard)) delete(chat_id)
def inline(message_id, chat_id, query_data, query_id, bot_language): try: if query_data in settingss or query_data in qualities: if query_data == "quality": keyboard = qualities_keyboard elif query_data == "bot_language": if users[chat_id]['bot_language'] != "en": users[chat_id]['bot_language'] = "en" else: users[chat_id]['bot_language'] = bot_language keyboard = create_keyboard(settingss, chat_id) elif query_data in qualities: users[chat_id]['quality'] = query_data keyboard = create_keyboard(settingss, chat_id) try: bot.editMessageReplyMarkup( chat_id, message_id, reply_markup=InlineKeyboardMarkup(keyboard)) except error.BadRequest: pass bot.answerCallbackQuery( query_id, translate(users[chat_id]['bot_language'], "DONE ✅")) elif "artist" in query_data: keyboard = [] link = api_artist % query_data.split("/")[4] try: url = reque(query_data.replace("down", ""), chat_id, True).json() except AttributeError: return if "album" in query_data: keyboard += [[ InlineKeyboardButton("{} - {}".format( a['title'], a['release_date']), callback_data=a['link']) ] for a in url['data']] keyboard.append([ InlineKeyboardButton(queries['back']['text'], callback_data=link) ]) elif "down" in query_data: if ans == "2": if users[chat_id]['c_downloads'] == 3: bot.answerCallbackQuery( query_id, translate( users[chat_id]['bot_language'], "Wait the end and repeat the step, did you think you could download how much songs you wanted? ;)" ), show_alert=True) return else: users[chat_id]['c_downloads'] += 1 bot.answerCallbackQuery( query_id, translate(users[chat_id]['bot_language'], "Songs are downloading ⬇️")) for a in url['data']: Link("https://www.deezer.com/track/%d" % a['id'], chat_id, users[chat_id]['quality'], message_id) if ans == "2": users[chat_id]['c_downloads'] += 1 if ans == "2": users[chat_id]['c_downloads'] -= 1 elif "radio" in query_data or "top" in query_data: if "radio" in query_data: method = "radio" else: method = "top?limit=30" keyboard += [[ InlineKeyboardButton( "{} - {}".format(a['artist']['name'], a['title']), callback_data="https://www.deezer.com/track/%d" % a['id']) ] for a in url['data']] keyboard.append([ InlineKeyboardButton("GET ALL ⬇️", callback_data="{}/{}/down".format( link, method)) ]) keyboard.append([ InlineKeyboardButton(queries['back']['text'], callback_data=link) ]) elif "related" in query_data: keyboard = [[ InlineKeyboardButton( "{} - {}".format(a['name'], a['nb_fan']), callback_data=api_artist % str(a['id'])) ] for a in url['data']] keyboard.append([ InlineKeyboardButton(queries['back']['text'], callback_data=link) ]) else: keyboard = [ [ InlineKeyboardButton( queries['top']['text'], callback_data=queries['top']['query'] % link), InlineKeyboardButton( queries['albums']['text'], callback_data=queries['albums']['query'] % link) ], [ InlineKeyboardButton( queries['radio']['text'], callback_data=queries['radio']['query'] % link), InlineKeyboardButton( queries['related']['text'], callback_data=queries['related']['query'] % link) ] ] bot.editMessageMedia( chat_id, message_id, media=InputMediaPhoto( url['picture_xl'], caption=( send_image_artist_query % (url['name'], url['nb_album'], url['nb_fan'])))) try: bot.editMessageReplyMarkup( chat_id, message_id, reply_markup=InlineKeyboardMarkup(keyboard)) except error.BadRequest: pass else: tags = query_data.split("_") if tags[0] == "Infos with too many bytes": bot.answerCallbackQuery( query_id, translate(users[chat_id]['bot_language'], query_data)) elif len(tags) == 4: bot.answerCallbackQuery(query_id, (tags_query % (tags[0], tags[1], tags[2], tags[3])), show_alert=True) else: if ans == "2": if users[chat_id]['c_downloads'] == 3: bot.answerCallbackQuery( query_id, translate( users[chat_id]['bot_language'], "Wait the end and repeat the step, did you think you could download how much songs you wanted? ;)" ), show_alert=True) return else: users[chat_id]['c_downloads'] += 1 bot.answerCallbackQuery( query_id, translate(users[chat_id]['bot_language'], "Song is downloading")) Link(query_data, chat_id, users[chat_id]['quality'], message_id) except TelegramError: pass
def left_member(update: Update, context: CallbackContext): chat = update.effective_chat # type: Optional[Chat] should_goodbye, cust_goodbye, goodbye_type = sql.get_gdbye_pref(chat.id) cust_goodbye = markdown_to_html(cust_goodbye) if should_goodbye: left_mem = update.effective_message.left_chat_member gban_checks = get_gbanned_user(left_mem.id) spamwatch_banned = client.get_ban(left_mem.id) if left_mem: # Ignore bot being kicked if left_mem.id == context.bot.id: return ### BAN CHECKERS ### # Ignore gbanned users if gban_checks: return # Ignore spamwatch banned users if spamwatch_banned: return # Give the owner a special goodbye if left_mem.id == OWNER_ID: update.effective_message.reply_text("RIP Master") return # if media goodbye, use appropriate function for it if goodbye_type != sql.Types.TEXT and goodbye_type != sql.Types.BUTTON_TEXT: ENUM_FUNC_MAP[goodbye_type](chat.id, cust_goodbye) return first_name = left_mem.first_name or "PersonWithNoName" # edge case of empty name - occurs for some bugs. if cust_goodbye: if left_mem.last_name: fullname = "{} {}".format(first_name, left_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_html(left_mem.id, first_name) if left_mem.username: username = "******" + escape(left_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets(cust_goodbye, VALID_WELCOME_FORMATTERS) res = valid_format.format(first=escape(first_name), last=escape(left_mem.last_name or first_name), fullname=escape(fullname), username=username, mention=mention, count=count, chatname=escape(chat.title), id=left_mem.id) buttons = sql.get_gdbye_buttons(chat.id) keyb = build_keyboard(buttons) else: res = sql.DEFAULT_GOODBYE keyb = [] keyboard = InlineKeyboardMarkup(keyb) send(update, context, res, keyboard, sql.DEFAULT_GOODBYE)
def verify_welcome(update, context, chat_id): user_id = update.effective_user.id is_clicked = sql.get_chat_userlist(chat_id) if user_id not in list(is_clicked): send_message( update.effective_message, tl( update.effective_message, "Anda sedang tidak dalam mode verifikasi, jika anda sedang di bisukan, anda dapat meminta tolong pada admin di grup yang bersangkutan" )) return elif user_id in list(is_clicked) and is_clicked[user_id] == True: send_message( update.effective_message, tl( update.effective_message, "Anda sedang tidak dalam mode verifikasi, jika anda sedang di bisukan, anda dapat meminta tolong pada admin di grup yang bersangkutan" )) return verify_code = [ "🙏", "👈", "👉", "👇", "👆", "❤️", "🅰️", "🅱️", "0️⃣", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟" ] print(len(verify_code)) real_btn = random.choice(verify_code) verify_code.remove(real_btn) verbox = (random.randint(1, 3), random.randint(1, 3)) buttons = [] linebox = [] was_set = False for x in range(3): x += 1 for y in range(3): y += 1 if verbox[0] == y and verbox[1] == x: was_set = True linebox.append( InlineKeyboardButton( text=real_btn, callback_data="verify_me(y|{}|{})".format( user_id, chat_id))) else: verify_emoji = random.choice(verify_code) linebox.append( InlineKeyboardButton( text=verify_emoji, callback_data="verify_me(n|{}|{})".format( user_id, chat_id))) verify_code.remove(verify_emoji) buttons.append(linebox) linebox = [] if not was_set: verbox = (random.randint(1, 3), random.randint(1, 3)) linebox[verbox[0] - 1][verbox[1] - 1] = InlineKeyboardButton( text=real_btn, callback_data="verify_me(y|{}|{})".format(user_id, chat_id)) buttons.append([ InlineKeyboardButton(text="Refresh", callback_data="verify_me(re|{}|{})".format( user_id, chat_id)) ]) context.bot.send_photo( user_id, photo=open( "emilia/modules/helper_funcs/emojis/" + verify_code_images[real_btn], 'rb'), caption=tl(update.effective_message, "Tolong pilih emoji yang sama dibawah ini:") + "\n" + tl(update.effective_message, "Jika tidak ada emoji yang sama, harap klik tombol refresh"), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons))
def create_menu(options): return InlineKeyboardMarkup([[ InlineKeyboardButton(i[0], callback_data=i[1]) for i in list(options) ]])
def settings_button(bot: Bot, update: Update): query = update.callback_query user = update.effective_user mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data) prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data) next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data) back_match = re.match(r"stngs_back\((.+?)\)", query.data) try: if mod_match: chat_id = mod_match.group(1) module = mod_match.group(2) chat = bot.get_chat(chat_id) text = "*{}* has the following settings for the *{}* module:\n\n".format(escape_markdown(chat.title), CHAT_SETTINGS[ module].__mod_name__) + \ CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id) query.message.reply_text( text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="🏃🏻♂️Back🏃🏻♂️", callback_data="stngs_back({})".format(chat_id)) ]])) elif prev_match: chat_id = prev_match.group(1) curr_page = int(prev_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text( "Hi there! There are quite a few settings for {} - go ahead and pick what " "you're interested in.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, CHAT_SETTINGS, "stngs", chat=chat_id))) elif next_match: chat_id = next_match.group(1) next_page = int(next_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text( "Hi there! There are quite a few settings for {} - go ahead and pick what " "you're interested in.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, CHAT_SETTINGS, "stngs", chat=chat_id))) elif back_match: chat_id = back_match.group(1) chat = bot.get_chat(chat_id) query.message.reply_text( text= "Hi there! There are quite a few settings for {} - go ahead and pick what " "you're interested in.".format(escape_markdown(chat.title)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id))) # ensure no spinny white circle bot.answer_callback_query(query.id) query.message.delete() except BadRequest as excp: if excp.message == "Message is not modified": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "Message can't be deleted": pass else: LOGGER.exception("Exception in settings buttons. %s", str(query.data))
def left_member(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] should_goodbye, cust_goodbye, cust_content, goodbye_type = sql.get_gdbye_pref( chat.id) cust_goodbye = markdown_to_html(cust_goodbye) if should_goodbye: left_mem = update.effective_message.left_chat_member if left_mem: if is_user_gbanned(left_mem.id): return # Ignore bot being kicked if left_mem.id == bot.id: return # Give the owner a special goodbye if left_mem.id == OWNER_ID: update.effective_message.reply_text( "Well, My mater have left, The party now ended!") return # if media goodbye, use appropriate function for it if goodbye_type != sql.Types.TEXT and goodbye_type != sql.Types.BUTTON_TEXT: reply = update.message.message_id cleanserv = sql.clean_service(chat.id) # Clean service welcome if cleanserv: try: dispatcher.bot.delete_message( chat.id, update.message.message_id) except BadRequest: pass reply = False # Formatting text first_name = left_mem.first_name or "PersonWithNoName" # edge case of empty name - occurs for some bugs. if left_mem.last_name: fullname = "{} {}".format(first_name, left_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_html(left_mem.id, first_name) if left_mem.username: username = "******" + escape(left_mem.username) else: username = mention formatted_text = cust_goodbye.format( first=escape(first_name), last=escape(left_mem.last_name or first_name), fullname=escape(fullname), username=username, mention=mention, count=count, chatname=escape(chat.title), id=left_mem.id) # Build keyboard buttons = sql.get_gdbye_buttons(chat.id) keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) # Send message ENUM_FUNC_MAP[goodbye_type](chat.id, cust_content, caption=cust_goodbye, reply_markup=keyboard, parse_mode="markdown", reply_to_message_id=reply) return first_name = left_mem.first_name or "PersonWithNoName" # edge case of empty name - occurs for some bugs. if cust_goodbye: if left_mem.last_name: fullname = "{} {}".format(first_name, left_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_html(left_mem.id, first_name) if left_mem.username: username = "******" + escape(left_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_goodbye, VALID_WELCOME_FORMATTERS) res = valid_format.format(first=escape(first_name), last=escape(left_mem.last_name or first_name), fullname=escape(fullname), username=username, mention=mention, count=count, chatname=escape(chat.title), id=left_mem.id) buttons = sql.get_gdbye_buttons(chat.id) keyb = build_keyboard(buttons) else: res = sql.DEFAULT_GOODBYE keyb = [] keyboard = InlineKeyboardMarkup(keyb) send(update, res, keyboard, sql.DEFAULT_GOODBYE)
def welcome(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat # type: Optional[Chat] # if no args, show current replies. if len(args) == 0 or args[0].lower() == "noformat": noformat = args and args[0].lower() == "noformat" pref, welcome_m, cust_content, welcome_type = sql.get_welc_pref( chat.id) prev_welc = sql.get_clean_pref(chat.id) if prev_welc: prev_welc = True else: prev_welc = False cleanserv = sql.clean_service(chat.id) getcur, cur_value, cust_text = sql.welcome_security(chat.id) if getcur: welcsec = "True " else: welcsec = "False " if cur_value[:1] == "0": welcsec += "(Muted forever until user clicked the button)" else: welcsec += "(Muting user for {})".format(cur_value) text = "This chat has it's welcome setting set to: `{}`\n".format(pref) text += "Deleting old welcome message: `{}`\n".format(prev_welc) text += "Deleting service message: `{}`\n".format(cleanserv) text += "Muting users when they joined: `{}`\n".format(welcsec) text += "Mute button text: `{}`\n".format(cust_text) text += "\n*The welcome message (not filling the {}) is:*" update.effective_message.reply_text(text, parse_mode=ParseMode.MARKDOWN) if welcome_type == sql.Types.BUTTON_TEXT or welcome_type == sql.Types.TEXT: buttons = sql.get_welc_buttons(chat.id) if noformat: welcome_m += revert_buttons(buttons) update.effective_message.reply_text(welcome_m) else: keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) send(update, welcome_m, keyboard, sql.DEFAULT_WELCOME) else: buttons = sql.get_welc_buttons(chat.id) if noformat: welcome_m += revert_buttons(buttons) ENUM_FUNC_MAP[welcome_type](chat.id, cust_content, caption=welcome_m) else: keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) ENUM_FUNC_MAP[welcome_type](chat.id, cust_content, caption=welcome_m, reply_markup=keyboard, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) elif len(args) >= 1: if args[0].lower() in ("on", "yes"): sql.set_welc_preference(str(chat.id), True) update.effective_message.reply_text( "New member will be greeted with warm welcome message now!") elif args[0].lower() in ("off", "no"): sql.set_welc_preference(str(chat.id), False) update.effective_message.reply_text( "I'm sulking, Not saying hello anymore :V") else: # idek what you're writing, say yes or no update.effective_message.reply_text( "Please choose 'on/yes' or 'off/no' only!")
def test_edit_message_reply_markup_without_required(self, bot): new_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text='test', callback_data='1')]]) with pytest.raises(ValueError, match='Both chat_id and message_id are required when'): bot.edit_message_reply_markup(reply_markup=new_markup)
def new_member(bot: Bot, update: Update): chat = update.effective_chat user = update.effective_user should_welc, cust_welcome, cust_content, welc_type = sql.get_welc_pref( chat.id) cust_welcome = markdown_to_html(cust_welcome) if should_welc: sent = None new_members = update.effective_message.new_chat_members for new_mem in new_members: # Give start information when add bot to group if is_user_gbanned(new_mem.id): return if new_mem.id == bot.id: bot.send_message( MESSAGE_DUMP, "I have been added to {} with ID: <pre>{}</pre> by <code>{}</code>" .format(chat.title, chat.id, user.id), parse_mode=ParseMode.HTML) bot.send_message( chat.id, f"Thanks {user.first_name} for adding me in {chat.title}! Don't forgot to checkout our news channel!" ) else: # If welcome message is media, send with appropriate function if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT: reply = update.message.message_id cleanserv = sql.clean_service(chat.id) # Clean service welcome if cleanserv: try: dispatcher.bot.delete_message( chat.id, update.message.message_id) except BadRequest: pass reply = False # Formatting text first_name = new_mem.first_name or "PersonWithNoName" # edge case of empty name - occurs for some bugs. if new_mem.last_name: fullname = "{} {}".format(first_name, new_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_html(new_mem.id, first_name) if new_mem.username: username = "******" + escape(new_mem.username) else: username = mention formatted_text = cust_welcome.format( first=escape(first_name), last=escape(new_mem.last_name or first_name), fullname=escape(fullname), username=username, mention=mention, count=count, chatname=escape(chat.title), id=new_mem.id) # Build keyboard buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) getsec, mutetime, custom_text = sql.welcome_security( chat.id) member = chat.get_member(new_mem.id) # If user ban protected don't apply security on him if is_user_ban_protected(chat, new_mem.id, chat.get_member(new_mem.id)): pass elif getsec: # If mute time is turned on if mutetime: if mutetime[:1] == "0": if member.can_send_messages is None or member.can_send_messages: try: bot.restrict_chat_member( chat.id, new_mem.id, can_send_messages=False) canrest = True except BadRequest: canrest = False else: canrest = False else: mutetime = extract_time( update.effective_message, mutetime) if member.can_send_messages is None or member.can_send_messages: try: bot.restrict_chat_member( chat.id, new_mem.id, until_date=mutetime, can_send_messages=False) canrest = True except BadRequest: canrest = False else: canrest = False # If security welcome is turned on if canrest: sql.add_to_userlist(chat.id, new_mem.id) keyb.append([ InlineKeyboardButton( text=str(custom_text), callback_data="check_bot_({})".format( new_mem.id)) ]) keyboard = InlineKeyboardMarkup(keyb) # Send message ENUM_FUNC_MAP[welc_type](chat.id, cust_content, caption=formatted_text, reply_markup=keyboard, parse_mode="markdown", reply_to_message_id=reply) return # else, move on first_name = new_mem.first_name or "PersonWithNoName" # edge case of empty name - occurs for some bugs. if cust_welcome: if new_mem.last_name: fullname = "{} {}".format(first_name, new_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_html(new_mem.id, first_name) if new_mem.username: username = "******" + escape(new_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS) res = valid_format.format(first=escape(first_name), last=escape(new_mem.last_name or first_name), fullname=escape(fullname), username=username, mention=mention, count=count, chatname=escape(chat.title), id=new_mem.id) buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) else: res = sql.DEFAULT_WELCOME.format(first=first_name) keyb = [] getsec, mutetime, custom_text = sql.welcome_security(chat.id) member = chat.get_member(new_mem.id) # If user ban protected don't apply security on him if is_user_ban_protected(chat, new_mem.id, chat.get_member(new_mem.id)): pass elif getsec: if mutetime: if mutetime[:1] == "0": if member.can_send_messages is None or member.can_send_messages: try: bot.restrict_chat_member( chat.id, new_mem.id, can_send_messages=False) canrest = True except BadRequest: canrest = False else: canrest = False else: mutetime = extract_time(update.effective_message, mutetime) if member.can_send_messages is None or member.can_send_messages: try: bot.restrict_chat_member( chat.id, new_mem.id, until_date=mutetime, can_send_messages=False) canrest = True except BadRequest: canrest = False else: canrest = False if canrest: sql.add_to_userlist(chat.id, new_mem.id) keyb.append([ InlineKeyboardButton( text=str(custom_text), callback_data="check_bot_({})".format( new_mem.id)) ]) keyboard = InlineKeyboardMarkup(keyb) sent = send(update, res, keyboard, sql.DEFAULT_WELCOME.format( first=first_name)) # type: Optional[Message] prev_welc = sql.get_clean_pref(chat.id) if prev_welc: try: bot.delete_message(chat.id, prev_welc) except BadRequest as excp: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id)
def warn(user: User, chat: Chat, reason: str, message: Message, warner: User = None) -> str: if is_user_admin(chat, user.id): # message.reply_text("Damn admins, They are too far to be One Punched!") return if user.id in TIGER_USERS: if warner: message.reply_text("Tigers cant be warned.") else: message.reply_text("Tiger triggered an auto warn filter!\n I can't warn tigers but they should avoid abusing this.") return if user.id in WHITELIST_USERS: if warner: message.reply_text("Wolf disasters are warn immune.") else: message.reply_text("Wolf Disaster triggered an auto warn filter!\nI can't warn wolves but they should avoid abusing this.") return if warner: warner_tag = mention_html(warner.id, warner.first_name) else: warner_tag = "Automated warn filter." limit, soft_warn = sql.get_warn_setting(chat.id) num_warns, reasons = sql.warn_user(user.id, chat.id, reason) if num_warns >= limit: sql.reset_warns(user.id, chat.id) if soft_warn: # punch chat.unban_member(user.id) reply = f"{limit} warnings, *Punches {mention_html(user.id, user.first_name)} with a normal punch!* " else: # ban chat.kick_member(user.id) reply = f"{limit} warnings, *Punches {mention_html(user.id, user.first_name)} with a Serious Punch* " for warn_reason in reasons: reply += f"\n - {html.escape(warn_reason)}" message.bot.send_sticker(chat.id, BAN_STICKER) # Saitama's sticker keyboard = [] log_reason = (f"<b>{html.escape(chat.title)}:</b>\n" f"#WARN_BAN\n" f"<b>Admin:</b> {warner_tag}\n" f"<b>User:</b> {mention_html(user.id, user.first_name)}\n" f"<b>Reason:</b> {reason}\n" f"<b>Counts:</b> <code>{num_warns}/{limit}</code>") else: keyboard = InlineKeyboardMarkup([{InlineKeyboardButton("Remove warn", callback_data="rm_warn({})".format(user.id))}]) reply = f"{mention_html(user.id, user.first_name)} has {num_warns}/{limit} warnings... watch out!" if reason: reply += f"\nReason for last warn:\n{html.escape(reason)}" log_reason = (f"<b>{html.escape(chat.title)}:</b>\n" f"#WARN\n" f"<b>Admin:</b> {warner_tag}\n" f"<b>User:</b> {mention_html(user.id, user.first_name)}\n" f"<b>Reason:</b> {reason}\n" f"<b>Counts:</b> <code>{num_warns}/{limit}</code>") try: message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML, quote=False) else: raise return log_reason
def new_member(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] should_welc, cust_welcome, welc_type = sql.get_welc_pref(chat.id) if should_welc: sent = None new_members = update.effective_message.new_chat_members for new_mem in new_members: # Give the owner a special welcome if new_mem.id == OWNER_ID: update.effective_message.reply_text( "Master is in the houseeee, let's get this party started!") continue # Give start information when add bot to group elif new_mem.id == bot.id: bot.send_message( MESSAGE_DUMP, "I have been added to {} with ID: <pre>{}</pre>".format( chat.title, chat.id), parse_mode=ParseMode.HTML) continue update.effective_message.reply_text("Thanks for adding me!") else: # If welcome message is media, send with appropriate function if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT: ENUM_FUNC_MAP[welc_type](chat.id, cust_welcome) return # else, move on first_name = new_mem.first_name or "PersonWithNoName" # edge case of empty name - occurs for some bugs. if cust_welcome: if new_mem.last_name: fullname = "{} {}".format(first_name, new_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_markdown(new_mem.id, escape_markdown(first_name)) if new_mem.username: username = "******" + escape_markdown(new_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS) res = valid_format.format( first=escape_markdown(first_name), last=escape_markdown(new_mem.last_name or first_name), fullname=escape_markdown(fullname), username=username, mention=mention, count=count, chatname=escape_markdown(chat.title), id=new_mem.id) buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) else: res = sql.DEFAULT_WELCOME.format(first=first_name) keyb = [] keyboard = InlineKeyboardMarkup(keyb) sent = send(update, res, keyboard, sql.DEFAULT_WELCOME.format( first=first_name)) # type: Optional[Message] #Clean service welcome if sql.clean_service(chat.id) == True: bot.delete_message(chat.id, update.message.message_id) #If user ban protected don't apply security on him if is_user_ban_protected(chat, new_mem.id, chat.get_member(new_mem.id)): continue #Security soft mode if sql.welcome_security(chat.id) == "soft": bot.restrict_chat_member(chat.id, new_mem.id, can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False, until_date=(int(time.time() + 24 * 60 * 60))) #Add "I'm not bot button if enabled hard security" if sql.welcome_security(chat.id) == "hard": update.effective_message.reply_text( "Hi {}, click on button below for been unmuted.". format(new_mem.first_name), reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="I'm not a bot!", callback_data="check_bot_({})".format( new_mem.id)) ]])) #Mute user bot.restrict_chat_member(chat.id, new_mem.id, can_send_messages=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False) prev_welc = sql.get_clean_pref(chat.id) if prev_welc: try: bot.delete_message(chat.id, prev_welc) except BadRequest as excp: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id)
from logging import getLogger # Self imports from meldebot.mel.gif import get_gifs from meldebot.mel.utils import send_typing_action, remove_command_message, get_username logger = getLogger(__name__) # Mort de Gana POLL MANAGER # POLL KEYBOARD POLL_KEYBOARD = InlineKeyboardMarkup([ [ InlineKeyboardButton("MEL", callback_data="vote MEL"), InlineKeyboardButton("MEL + 1", callback_data="vote MEL+1"), InlineKeyboardButton("MEL - 1", callback_data="vote MEL-1"), ], [ InlineKeyboardButton("MOTO", callback_data="vote MOTO"), ], ]) # POLL START def get_question(extra_text): question = "Mel o no?\n" if extra_text: question = "{}\n{}".format(extra_text, question) return question
def kang(bot: Bot, update: Update, args: List[str]): if os.path.isfile("kangsticker.png"): os.remove("kangsticker.png") msg = update.effective_message user = update.effective_user packname = f"c{user.id}_by_{bot.username}" kangsticker = "kangsticker.png" reply = msg.reply_to_message if reply: if reply.sticker: file_id = reply.sticker.file_id elif reply.photo: file_id = reply.photo[-1].file_id elif reply.document: file_id = reply.document.file_id else: msg.reply_text("Reply to an image or sticker to kang it.") return kang_file = bot.get_file(file_id) kang_file.download(kangsticker) if args: sticker_emoji = str(args[0]) elif reply.sticker and reply.sticker.emoji: sticker_emoji = reply.sticker.emoji else: sticker_emoji = "🤔" elif args and not reply: urlemoji = msg.text.split(" ") if len(urlemoji) == 3: png_sticker = urlemoji[1] sticker_emoji = urlemoji[2] elif len(urlemoji) == 2: png_sticker = urlemoji[1] sticker_emoji = "🤔" else: msg.reply_text("/kang <link> <emoji(s) [Optional]>") return try: urllib.urlretrieve(png_sticker, kangsticker) except HTTPError as HE: if HE.reason == 'Not Found': msg.reply_text("Image not found.") return elif HE.reason == 'Forbidden': msg.reply_text( "Couldn't access the provided link, The website might have blocked accessing to the website by bot or the website does not existed." ) return except URLError as UE: msg.reply_text(f"{UE.reason}") return except ValueError as VE: msg.reply_text( f"{VE}\nPlease try again using http or https protocol.") return else: msg.reply_text( "Please reply to a sticker, or an image to kang it!\nDo you know that you can kang image from website too? `/kang [picturelink] <emoji(s)>`.", parse_mode=ParseMode.MARKDOWN) return try: im = imresize(kangsticker) im.save(kangsticker, "PNG") bot.add_sticker_to_set(user_id=user.id, name=packname, png_sticker=open('kangsticker.png', 'rb'), emojis=sticker_emoji) msg.reply_text("I've added this sticker to your." + "\n" "Emoji(s):" + " " + sticker_emoji, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="I've added this sticker your", url=f"t.me/addstickers/{packname}") ]])) except OSError as e: msg.reply_text("I can only kang images sar.") print(e) return except TelegramError as e: if e.message == "Stickerset_invalid": makepack_internal(msg, user, open('kangsticker.png', 'rb'), sticker_emoji, bot) elif e.message == "Invalid sticker emojis": msg.reply_text("Invalid emoji(s).") elif e.message == "Stickers_too_much": msg.reply_text("Max packsize reached. Press F to pay respect.") print(e)
def init(update,context): bot = context.bot chat = chat_object(update) if chat.type == 'supergroup': row = CommunityRepository().getById(chat.id) if row: record = GroupRepository.SET_COMMUNITY default_community = 1 data = [(chat.title,chat.id)] data_group = [(default_community, chat.id)] CommunityRepository().update(data) GroupRepository().update_group_settings(record,data_group) message(update,context,"I updated the community on the database") else: buttons = [] buttons.append(InlineKeyboardButton('IT', callback_data='commIT')) buttons.append(InlineKeyboardButton('EN', callback_data='commEN')) buttons.append(InlineKeyboardButton('Close', callback_data='closeMenu')) menu = build_menu(buttons,2) bot.send_message(chat_id=update.effective_chat.id,text="Please select the language of the community",reply_markup=InlineKeyboardMarkup(menu)) else: message(update,context,"Attention! this command can only be used in public supergroups!")
def get(bot, update, notename, show_none=True, no_format=False): chat_id = update.effective_chat.id note = sql.get_note(chat_id, notename) message = update.effective_message # type: Optional[Message] if note: # If we're replying to a message, reply to that message (unless it's an error) if message.reply_to_message: reply_id = message.reply_to_message.message_id else: reply_id = message.message_id if note.is_reply: if MESSAGE_DUMP: try: bot.forward_message(chat_id=chat_id, from_chat_id=MESSAGE_DUMP, message_id=note.value) except BadRequest as excp: if excp.message == "Message to forward not found": message.reply_text( "This message seems to have been lost - I'll remove it " "from your notes list.") sql.rm_note(chat_id, notename) else: raise else: try: bot.forward_message(chat_id=chat_id, from_chat_id=chat_id, message_id=note.value) except BadRequest as excp: if excp.message == "Message to forward not found": message.reply_text( "Looks like the original sender of this note has deleted " "their message - sorry! Get your bot admin to start using a " "message dump to avoid this. I'll remove this note from " "your saved notes.") sql.rm_note(chat_id, notename) else: raise else: text = note.value keyb = [] parseMode = ParseMode.MARKDOWN buttons = sql.get_buttons(chat_id, notename) if no_format: parseMode = None text += revert_buttons(buttons) else: keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) try: if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT): bot.send_message(chat_id, text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard) else: ENUM_FUNC_MAP[note.msgtype](chat_id, note.file, caption=text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard) except BadRequest as excp: if excp.message == "Entity_mention_user_invalid": message.reply_text( "Looks like you tried to mention someone I've never seen before. If you really " "want to mention them, forward one of their messages to me, and I'll be able " "to tag them!") elif FILE_MATCHER.match(note.value): message.reply_text( "This note was an incorrectly imported file from another bot - I can't use " "it. If you really need it, you'll have to save it again. In " "the meantime, I'll remove it from your notes list.") sql.rm_note(chat_id, notename) else: message.reply_text( "This note could not be sent, as it is incorrectly formatted. Ask in " f"{SUPPORT_CHAT} if you can't figure out why!") LOGGER.exception("Could not parse message #%s in chat %s", notename, str(chat_id)) LOGGER.warning("Message was: %s", str(note.value)) return elif show_none: message.reply_text("This note doesn't exist")
def makepack_internal( update, context, msg, user, emoji, packname, packnum, png_sticker=None, tgs_sticker=None, ): name = user.first_name name = name[:50] try: extra_version = "" if packnum > 0: extra_version = " " + str(packnum) if png_sticker: success = context.bot.create_new_sticker_set( user.id, packname, f"{name}s " + extra_version, png_sticker=png_sticker, emojis=emoji, ) if tgs_sticker: success = context.bot.create_new_sticker_set( user.id, packname, f"{name}s " + extra_version, tgs_sticker=tgs_sticker, emojis=emoji, ) except TelegramError as e: print(e) if e.message == "Sticker set name is already occupied": msg.reply_text( "Your pack can be found [here](t.me/addstickers/%s)" % packname, parse_mode=ParseMode.MARKDOWN, ) elif e.message == "Peer_id_invalid" or "bot was blocked by the user": msg.reply_text( "Contact me in PM first.", reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text="Start", url=f"t.me/{context.bot.username}") ]]), ) elif e.message == "Internal Server Error: created sticker set not found (500)": msg.reply_text( "Sticker pack successfully created. Get it [here](t.me/addstickers/%s)" % packname, parse_mode=ParseMode.MARKDOWN, ) return if success: msg.reply_text( "Sticker pack successfully created. Get it [here](t.me/addstickers/%s)" % packname, parse_mode=ParseMode.MARKDOWN, ) else: msg.reply_text( "Failed to create sticker pack. Possibly due to blek mejik.")
def start(update, context): print("Received start command from chat_id: {}".format(update.effective_chat.id)) reply_markup = InlineKeyboardMarkup(main_menu) context.bot.send_message(chat_id=update.effective_chat.id, text="Sending menu. Select:", reply_markup=reply_markup)
def send_start(bot, update): #Try to remove old message try: query = update.callback_query query.message.delete() except: pass chat = update.effective_chat # type: Optional[Chat] first_name = update.effective_user.first_name text = PM_START keyboard = [[InlineKeyboardButton(text="🇮🇳 Language", callback_data="set_lang_")]] keyboard += [[InlineKeyboardButton(text="🛠 Reporting", callback_data="cntrl_panel_M"), InlineKeyboardButton(text="❔ Help", callback_data="help_back")]] update.effective_message.reply_text(PM_START.format(escape_markdown(first_name), bot.first_name), reply_markup=InlineKeyboardMarkup(keyboard), disable_web_page_preview=True, parse_mode=ParseMode.MARKDOWN)
def new_member(update: Update, context: CallbackContext): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[Message] chat_name = chat.title or chat.first or chat.username # type: Optional:[chat name] should_welc, cust_welcome, welc_type, welc_caption = sql.get_welc_pref(chat.id) welc_mutes = sql.welcome_mutes(chat.id) human_checks = sql.get_human_checks(user.id, chat.id) prev_welc = sql.get_clean_pref(chat.id) media = False no_mute = False try: for mem in msg.new_chat_members: user_id = mem.id except: LOGGER.log("User being added or no ID found for user.") gban_checks = get_gbanned_user(user_id) join_log = sql.get_join_event_pref(chat.id) join_members = msg.new_chat_members if should_welc: sent = None new_members = msg.new_chat_members for new_mem in new_members: spamwatch_banned = client.get_ban(new_mem.id) user_add = context.bot.get_chat_member(chat.id, user.id) # edge case of empty name - occurs for some bugs. first_name = new_mem.first_name or "PersonWithNoName" # Give the owner a special welcome log = "" if join_log == True: log += "<b>{}:</b>" \ "\n#WELCOME" \ "\n<b>A new user has joined:</b>" \ "\n<b>• User:</b> {}" \ "\n<b>• ID:</b> <code>{}</code>".format(escape(chat.title), mention_html(mem.id, mem.first_name), mem.id) if user.id != mem.id: log += "\n<b>• Added by:</b> {}".format(mention_html(user.id, user.first_name)) if new_mem.id == OWNER_ID: update.effective_message.reply_text("Master is in the houseeee, let's get this party started!") continue #### BAN CHECKERS #### # Ignore welc messages for gbanned users if gban_checks: continue # Ignore welc messages for SpamWatch banned users if spamwatch_banned: continue # Make bot greet admins elif new_mem.id == context.bot.id: update.effective_message.reply_text("Hey {}, I'm {}! Thank you for adding me to {}" " and be sure to check /help in PM for more commands and tricks!".format(user.first_name, context.bot.first_name, chat_name)) else: # If welcome message is media, send with appropriate function if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT: if welc_type == sql.Types.PHOTO: media = True type = 'photo' if welc_caption: res = format_welcome_message(welc_caption, first_name, chat, new_mem) buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) sent = send(update, context, cust_welcome, keyboard, sql.DEFAULT_WELCOME.format(first=first_name, chatname=chat_name), res, type) if sent: sql.set_clean_welcome(chat.id, sent.message_id) elif welc_type == sql.Types.VIDEO: media = True type = 'video' if welc_caption: res = format_welcome_message(welc_caption, first_name, chat, new_mem) buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) sent = send(update, context, cust_welcome, keyboard, sql.DEFAULT_WELCOME.format(first=first_name, chatname=chat_name), res, type) if sent: sql.set_clean_welcome(chat.id, sent.message_id) elif welc_type == sql.Types.DOCUMENT: media = True type = 'document' if welc_caption: res = format_welcome_message( welc_caption, first_name, chat, new_mem) buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) sent = send(update, context, cust_welcome, keyboard, sql.DEFAULT_WELCOME.format(first=first_name, chatname=chat_name), res, type) if sent: sql.set_clean_welcome(chat.id, sent.message_id) else: media = True ENUM_FUNC_MAP[welc_type](chat.id, cust_welcome) # else, move on if media == False: if welc_caption: res = format_welcome_message(welc_caption, first_name, chat, new_mem) buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) else: res = sql.DEFAULT_WELCOME.format(first=first_name, chatname=chat_name) keyb = [] keyboard = InlineKeyboardMarkup(keyb) sent = send(update, context, res, keyboard, sql.DEFAULT_WELCOME.format(first=first_name, chatname=chat_name)) # type: Optional[Message] #User exception from mutes: if is_user_ban_protected(chat, new_mem.id, chat.get_member(new_mem.id)) or human_checks or gban_checks: no_mute = True if not no_mute: #Join welcome: soft mute if welc_mutes == "soft": context.bot.restrict_chat_member(chat.id, new_mem.id, WELCOME_PERMISSIONS_SOFT, until_date=(int(time.time() + 24 * 60 * 60))) #Join welcome: strong mute if welc_mutes == "strong": mute_message = msg.reply_text("Hey {} (`{}`),\nClick the button below to prove you're human:".format(new_mem.first_name, new_mem.id), reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Tap here to speak", callback_data="user_join_({})".format(new_mem.id))]]), parse_mode=ParseMode.MARKDOWN) context.bot.restrict_chat_member(chat.id, new_mem.id, WELCOME_PERMISSIONS_STRONG) #Join welcome: aggressive mute elif welc_mutes == "aggressive": mute_message = msg.reply_text("Hey {} (`{}`),\nClick the button below to prove you're human:".format(new_mem.first_name, new_mem.id), reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Tap here to speak", callback_data="user_join_({})".format(new_mem.id))]]), parse_mode=ParseMode.MARKDOWN) context.bot.restrict_chat_member(chat.id, new_mem.id, WELCOME_PERMISSIONS_AGGRESSIVE) delete_join(update, context) if prev_welc: try: context.bot.delete_message(chat.id, prev_welc) except BadRequest as excp: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id) if not human_checks and welc_mutes == "aggressive": t = threading.Thread(target=aggr_mute_check, args=( context.bot, chat, mute_message.message_id, new_mem.id,)) t.start() return log return ""
def control_panel(bot, update): LOGGER.info("Control panel") chat = update.effective_chat user = update.effective_user # ONLY send help in PM if chat.type != chat.PRIVATE: update.effective_message.reply_text("Contact me in PM to access the control panel.", reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton(text="Control Panel", url=f"t.me/{bot.username}?start=controlpanel")]])) return #Support to run from command handler query = update.callback_query if query: query.message.delete() M_match = re.match(r"cntrl_panel_M", query.data) U_match = re.match(r"cntrl_panel_U", query.data) G_match = re.match(r"cntrl_panel_G", query.data) back_match = re.match(r"help_back", query.data) LOGGER.info(query.data) else: M_match = "ThaNos is the best bot" #LMAO, don't uncomment if M_match: text = "*Control panel* 🛠" keyboard = [[InlineKeyboardButton(text="👤 My settings", callback_data="cntrl_panel_U(1)")]] #Show connected chat and add chat settings button conn = connected(bot, update, chat, user.id, need_admin=False) if conn: chatG = bot.getChat(conn) #admin_list = chatG.get_administrators() #Unused variable #If user admin member = chatG.get_member(user.id) if member.status in ('administrator', 'creator'): text += f"\nConnected chat - *{chatG.title}* (you {member.status})" keyboard += [[InlineKeyboardButton(text="👥 Group settings", callback_data="cntrl_panel_G_back")]] elif user.id in SUDO_USERS: text += f"\nConnected chat - *{chatG.title}* (you sudo)" keyboard += [[InlineKeyboardButton(text="👥 Group settings (SUDO)", callback_data="cntrl_panel_G_back")]] else: text += f"\nConnected chat - *{chatG.title}* (you aren't an admin!)" else: text += "\nNo chat connected!" keyboard += [[InlineKeyboardButton(text="Back", callback_data="bot_start")]] update.effective_message.reply_text(text, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode=ParseMode.MARKDOWN) elif U_match: mod_match = re.match(r"cntrl_panel_U_module\((.+?)\)", query.data) back_match = re.match(r"cntrl_panel_U\((.+?)\)", query.data) chatP = update.effective_chat # type: Optional[Chat] if mod_match: module = mod_match.group(1) R = CHAT_SETTINGS[module].__user_settings__(bot, update, user) text = "You has the following settings for the *{}* module:\n\n".format( CHAT_SETTINGS[module].__mod_name__) + R[0] keyboard = R[1] keyboard += [[InlineKeyboardButton(text="Back", callback_data="cntrl_panel_U(1)")]] query.message.reply_text(text=text, arse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)) elif back_match: text = "*User control panel* 🛠" query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(paginate_modules(user.id, 0, USER_SETTINGS, "cntrl_panel_U"))) elif G_match: mod_match = re.match(r"cntrl_panel_G_module\((.+?)\)", query.data) prev_match = re.match(r"cntrl_panel_G_prev\((.+?)\)", query.data) next_match = re.match(r"cntrl_panel_G_next\((.+?)\)", query.data) back_match = re.match(r"cntrl_panel_G_back", query.data) chatP = chat conn = connected(bot, update, chat, user.id) if not conn == False: chat = bot.getChat(conn) else: query.message.reply_text(text="Error with connection to chat") exit(1) if mod_match: module = mod_match.group(1) R = CHAT_SETTINGS[module].__chat_settings__(bot, update, chat, chatP, user) if type(R) is list: text = R[0] keyboard = R[1] else: text = R keyboard = [] text = "*{}* has the following settings for the *{}* module:\n\n".format( escape_markdown(chat.title), CHAT_SETTINGS[module].__mod_name__) + text keyboard += [[InlineKeyboardButton(text="Back", callback_data="cntrl_panel_G_back")]] query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)) elif prev_match: chat_id = prev_match.group(1) curr_page = int(prev_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text(tld(user.id, "send-group-settings").format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, 0, CHAT_SETTINGS, "cntrl_panel_G", chat=chat_id))) elif next_match: chat_id = next_match.group(1) next_page = int(next_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text(tld(user.id, "send-group-settings").format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, 0, CHAT_SETTINGS, "cntrl_panel_G", chat=chat_id))) elif back_match: text = "Test" query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(paginate_modules(user.id, 0, CHAT_SETTINGS, "cntrl_panel_G")))
def verify_button_pressed(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] query = update.callback_query # type: Optional[CallbackQuery] match = re.match(r"verify_me\((.+?)\)", query.data) match = match.group(1).split("|") is_ok = match[0] user_id = match[1] chat_id = match[2] message = update.effective_message # type: Optional[Message] print("-> {} was clicked welcome verify button".format(user.id)) if is_ok == "y": if context.bot.getChatMember(chat_id, user_id).status in ('left'): query.answer( text=tl(update.effective_message, "Failed: user left chat")) return try: context.bot.restrict_chat_member( chat_id, user_id, permissions=ChatPermissions(can_send_messages=True, can_send_media_messages=True, can_send_polls=True, can_send_other_messages=True, can_add_web_page_previews=True, can_change_info=True, can_invite_users=True, can_pin_messages=True)) sql.add_to_userlist(chat_id, user_id, True) sql.rm_from_timeout(chat_id, user_id) except BadRequest as err: if not update.effective_chat.get_member( context.bot.id).can_restrict_members: query.answer(text=tl( update.effective_message, "Saya tidak dapat membatasi orang disini, tanya admin untuk unmute!" )) else: query.answer(text="Error: " + str(err)) return chat_name = context.bot.get_chat(chat_id).title # query.message.delete() # context.bot.send_photo(chat.id, photo="https://telegra.ph/file/06d2c5ec80af3858c2d4b.jpg", caption=tl(update.effective_message, "*Berhasil!*\n\nKerja bagus manusia, kini Anda dapat chatting di: *{}*").format(chat_name), parse_mode="markdown") context.bot.edit_message_media( chat.id, message_id=query.message.message_id, media=InputMediaPhoto( media=open("emilia/modules/helper_funcs/emojis/done.jpg", 'rb'), caption=tl( update.effective_message, "*Berhasil!*\n\nKerja bagus manusia, kini Anda dapat chatting di: *{}*" ).format(chat_name), parse_mode="markdown")) query.answer(text=tl( update.effective_message, "Berhasil! Anda dapat chatting di {} sekarang").format(chat_name), show_alert=True) elif is_ok == "re": user_id = update.effective_user.id is_clicked = sql.get_chat_userlist(chat_id) if user_id not in list(is_clicked): context.bot.edit_message_text( chat.id, message_id=query.message.message_id, text=tl( update.effective_message, "Anda sedang tidak dalam mode verifikasi, jika anda sedang di bisukan, anda dapat meminta tolong pada admin di grup yang bersangkutan" )) return query.answer(text=tl(update.effective_message, "Error"), show_alert=False) elif user_id in list(is_clicked) and is_clicked[user_id] == True: context.bot.edit_message_text( chat.id, message_id=query.message.message_id, text=tl( update.effective_message, "Anda sedang tidak dalam mode verifikasi, jika anda sedang di bisukan, anda dapat meminta tolong pada admin di grup yang bersangkutan" )) return query.answer(text=tl(update.effective_message, "Error"), show_alert=False) verify_code = [ "🙏", "👈", "👉", "👇", "👆", "❤️", "🅰️", "🅱️", "0️⃣", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟" ] real_btn = random.choice(verify_code) print(real_btn) verify_code.remove(real_btn) verbox = (random.randint(1, 3), random.randint(1, 3)) buttons = [] linebox = [] was_set = False for x in range(3): x += 1 for y in range(3): y += 1 if verbox[0] == y and verbox[1] == x: was_set = True print("button was set to " + real_btn + "at " + str(verbox[0]) + " - " + str(verbox[1])) linebox.append( InlineKeyboardButton( text=real_btn, callback_data="verify_me(y|{}|{})".format( user_id, chat_id))) else: verify_emoji = random.choice(verify_code) linebox.append( InlineKeyboardButton( text=verify_emoji, callback_data="verify_me(n|{}|{})".format( user_id, chat_id))) verify_code.remove(verify_emoji) buttons.append(linebox) linebox = [] if not was_set: verbox = (random.randint(1, 3), random.randint(1, 3)) linebox[verbox[0] - 1][verbox[1] - 1] = InlineKeyboardButton( text=real_btn, callback_data="verify_me(y|{}|{})".format(user_id, chat_id)) print("[x] button was set to " + real_btn + "at " + str(verbox[0]) + " - " + str(verbox[1])) buttons.append([ InlineKeyboardButton(text="Refresh", callback_data="verify_me(re|{}|{})".format( user_id, chat_id)) ]) # query.message.delete() # context.bot.send_photo(chat.id, photo=open("emilia/modules/helper_funcs/emojis/" + verify_code_images[real_btn], 'rb'), caption=tl(update.effective_message, "Tolong pilih emoji yang sama dibawah ini:") + "\n" + tl(update.effective_message, "Jika tidak ada emoji yang sama, harap klik tombol refresh"), parse_mode="markdown", reply_markup=InlineKeyboardMarkup(buttons)) context.bot.edit_message_media( chat.id, message_id=query.message.message_id, media=InputMediaPhoto( media=open( "emilia/modules/helper_funcs/emojis/" + verify_code_images[real_btn], 'rb'), caption=tl(update.effective_message, "Tolong pilih emoji yang sama dibawah ini:") + "\n" + tl( update.effective_message, "Jika tidak ada emoji yang sama, harap klik tombol refresh" ), parse_mode="markdown"), reply_markup=InlineKeyboardMarkup(buttons)) query.answer(text=tl(update.effective_message, "Done"), show_alert=False) else: # query.message.delete() # context.bot.send_photo(chat.id, photo=open("emilia/modules/helper_funcs/emojis/fail.jpg", 'rb'), caption=tl(update.effective_message, "Maaf robot, kamu telah salah klik tombol verifikasi.\n\nCoba lagi dengan klik tombol verifikasi pada pesan selamat datang."), parse_mode="markdown") context.bot.edit_message_media( chat.id, message_id=query.message.message_id, media=InputMediaPhoto( media=open("emilia/modules/helper_funcs/emojis/fail.jpg", 'rb'), caption=tl( update.effective_message, "Maaf robot, kamu telah salah klik tombol verifikasi.\n\nCoba lagi dengan klik tombol verifikasi pada pesan selamat datang." ), parse_mode="markdown")) query.answer(text=tl( update.effective_message, "Gagal! Kamu telah salah mengklik tombol verifikasi"), show_alert=True)
"type": "postback", "title": "Examples", "payload": "OXFORD_DIC_EXAMPLES." + phrase }, { "type": "postback", "title": "Synonyms-Antonyms", "payload": "OXFORD_DIC_SYNONYMS." + phrase }, { "type": "postback", "title": "Pronunciation", "payload": "OXFORD_DIC_PRONUNCIATION." + phrase }] bot.sendPhoto(user_id, "https://i.ibb.co/71bh29h/pod.png") #bot.send_image_url(user_id, "https://image.ibb.co/kEx6oK/phrase_of_the_day.png") titles = [x['title'] for x in buttons] button_list = [InlineKeyboardButton(x, callback_data=x) for x in titles] reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=1)) bot.sendMessage(user_id, text, reply_markup=reply_markup) #bot.send_button_message(user_id, text, buttons) s_m_bytes = user_state_collection.posts.find_one({'user_id': user_id}) user_state_machine = pickle.loads(s_m_bytes['state_machine']) user_state_machine.data["examples"] = dic["examples"] user_state_machine.data["attachment"] = dic["attachment"] s_m_bytes = pickle.dumps(user_state_machine) post = {'user_id': user_id, 'state_machine': Binary(s_m_bytes)} user_state_collection.posts.update_one({'user_id': user_id}, {"$set": post}, upsert=False)
def menu(update, context): global free infos_chat = update.effective_chat chat_id = infos_chat.id infos_message = update.effective_message date = infos_message.date.timestamp() text = infos_message.text caption = infos_message.caption message_id = infos_message.message_id is_audio = infos_message.audio is_voice = infos_message.voice things = infos_message.entities infos_user = update.effective_user if not authorized(chat_id, date): return if not text: text = caption if not view_db(user_exist % chat_id): statisc(chat_id, "USERS") bot.sendMessage(chat_id, help_message, reply_markup=InlineKeyboardMarkup(first_time_keyboard)) return try: bot_language = infos_user.language_code except AttributeError: bot_language = "en" init_user(chat_id, bot_language) if text == "/start": sendPhoto(chat_id, open(photo, "rb"), start_message) keyboard = [ [ InlineKeyboardButton( queries['s_art']['text'], switch_inline_query_current_chat=queries['s_art']['query'] % ""), InlineKeyboardButton( queries['s_alb']['text'], switch_inline_query_current_chat=queries['s_alb']['query'] % "") ], [ InlineKeyboardButton( queries['s_pla']['text'], switch_inline_query_current_chat=queries['s_pla']['query'] % ""), InlineKeyboardButton( queries['s_lbl']['text'], switch_inline_query_current_chat=queries['s_lbl']['query'] % "") ], [ InlineKeyboardButton( queries['s_trk']['text'], switch_inline_query_current_chat=queries['s_trk']['query'] % ""), InlineKeyboardButton( queries['s_']['text'], switch_inline_query_current_chat=queries['s_']['query'] % ".chart.") ], ] sendMessage(chat_id, "Choose what you prefer", reply_markup=InlineKeyboardMarkup(keyboard)) elif text == "/info": sendMessage( chat_id, info_msg % (version, bot_name, creator, donation_link, group_link, statisc(chat_id, "USERS"), statisc(chat_id, "TRACKS"))) elif text == "/settings": sendMessage(chat_id, "Settings", reply_markup=InlineKeyboardMarkup( create_keyboard(settingss, chat_id))) elif text == "/detect": sendMessage(chat_id, "Send the audio or voice message to identify the song") elif text == "/help": bot.sendMessage(chat_id, help_message) elif is_audio or is_voice: if is_audio: file_id = is_audio['file_id'] else: file_id = is_voice['file_id'] Thread(target=Audio, args=(file_id, chat_id)).start() elif text: if chat_id in roots and "the cat is on the table" in text: what = text.split("the cat is on the table ")[-1] if what == "1": free = 1 elif what == "0": free = 0 elif len(things) == 0: keyboard = [ [ InlineKeyboardButton( queries['s_art']['text'], switch_inline_query_current_chat=queries['s_art'] ['query'] % text), InlineKeyboardButton( queries['s_alb']['text'], switch_inline_query_current_chat=queries['s_alb'] ['query'] % text) ], [ InlineKeyboardButton( queries['s_pla']['text'], switch_inline_query_current_chat=queries['s_pla'] ['query'] % text), InlineKeyboardButton( queries['s_lbl']['text'], switch_inline_query_current_chat=queries['s_lbl'] ['query'] % text) ], [ InlineKeyboardButton( queries['s_trk']['text'], switch_inline_query_current_chat=queries['s_trk'] ['query'] % text), InlineKeyboardButton( queries['s_']['text'], switch_inline_query_current_chat=queries['s_']['query'] % text) ], ] sendMessage(chat_id, "Press", reply_markup=InlineKeyboardMarkup(keyboard)) else: if ans == "2" and users[chat_id]['c_downloads'] == 3: sendMessage( chat_id, "Wait the end and repeat the step, did you think you could download how much songs you wanted? ;)" ) else: if ans == "2": users[chat_id]['c_downloads'] += 1 linked = infos_message.parse_entity(things[0]) Thread(target=Link, args=(linked, chat_id, users[chat_id]['quality'], message_id)).start()
def get(update, context, notename, show_none=True, no_format=False): bot = context.bot chat_id = update.effective_message.chat.id note_chat_id = update.effective_chat.id note = sql.get_note(note_chat_id, notename) message = update.effective_message # type: Optional[Message] if note: if MessageHandlerChecker.check_user(update.effective_user.id): return # If we're replying to a message, reply to that message (unless it's an error) if message.reply_to_message: reply_id = message.reply_to_message.message_id else: reply_id = message.message_id if note.is_reply: if JOIN_LOGGER: try: bot.forward_message(chat_id=chat_id, from_chat_id=JOIN_LOGGER, message_id=note.value) except BadRequest as excp: if excp.message == "Message to forward not found": message.reply_text( "This message seems to have been lost - I'll remove it " "from your notes list.") sql.rm_note(note_chat_id, notename) else: raise else: try: bot.forward_message(chat_id=chat_id, from_chat_id=chat_id, message_id=note.value) except BadRequest as excp: if excp.message == "Message to forward not found": message.reply_text( "Looks like the original sender of this note has deleted " "their message - sorry! Get your bot admin to start using a " "message dump to avoid this. I'll remove this note from " "your saved notes.") sql.rm_note(note_chat_id, notename) else: raise else: VALID_NOTE_FORMATTERS = [ 'first', 'last', 'fullname', 'username', 'id', 'chatname', 'mention' ] valid_format = escape_invalid_curly_brackets( note.value, VALID_NOTE_FORMATTERS) if valid_format: if not no_format: if '%%%' in valid_format: split = valid_format.split('%%%') if all(split): text = random.choice(split) else: text = valid_format else: text = valid_format else: text = valid_format text = text.format( first=escape_markdown(message.from_user.first_name), last=escape_markdown(message.from_user.last_name or message.from_user.first_name), fullname=escape_markdown( " ".join([ message.from_user.first_name, message.from_user. last_name ] if message.from_user.last_name else [message.from_user.first_name])), username="******" + message.from_user.username if message.from_user.username else mention_markdown( message.from_user.id, message.from_user.first_name), mention=mention_markdown(message.from_user.id, message.from_user.first_name), chatname=escape_markdown( message.chat.title if message.chat.type != "private" else message.from_user.first_name), id=message.from_user.id) else: text = "" keyb = [] parseMode = ParseMode.MARKDOWN buttons = sql.get_buttons(note_chat_id, notename) if no_format: parseMode = None text += revert_buttons(buttons) else: keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) try: if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT): bot.send_message(chat_id, text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard) else: ENUM_FUNC_MAP[note.msgtype](chat_id, note.file, caption=text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard) except BadRequest as excp: if excp.message == "Entity_mention_user_invalid": message.reply_text( "Looks like you tried to mention someone I've never seen before. If you really " "want to mention them, forward one of their messages to me, and I'll be able " "to tag them!") elif FILE_MATCHER.match(note.value): message.reply_text( "This note was an incorrectly imported file from another bot - I can't use " "it. If you really need it, you'll have to save it again. In " "the meantime, I'll remove it from your notes list.") sql.rm_note(note_chat_id, notename) else: message.reply_text( "This note could not be sent, as it is incorrectly formatted. Ask in " f"@{SUPPORT_CHAT} if you can't figure out why!") LOGGER.exception("Could not parse message #%s in chat %s", notename, str(note_chat_id)) LOGGER.warning("Message was: %s", str(note.value)) return elif show_none: message.reply_text("This note doesn't exist")
def Audio(audio, chat_id): global spo global is_audio is_audio = 1 audi = "{}{}.ogg".format(loc_dir, audio) try: bot.getFile(audio).download(audi) except TelegramError: sendMessage( chat_id, "File sent is too big, please send a file lower than 20 MB") is_audio = 0 return audio = acrcloud.recognizer(audi) is_audio = 0 try: os.remove(audi) except FileNotFoundError: pass if audio['status']['msg'] != "Success": sendMessage(chat_id, "Sorry cannot detect the song from audio :(, retry...") return infos = audio['metadata']['music'][0] artist = infos['artists'][0]['name'] track = infos['title'] album = infos['album']['name'] try: date = infos['release_date'] album += "_%s" % date except KeyError: album += "_" try: label = infos['label'] album += "_%s" % label except KeyError: album += "_" try: genre = infos['genres'][0]['name'] album += "_%s" % genre except KeyError: album += "_" if len(album) > 64: album = "Infos with too many bytes" try: song = "{} - {}".format(track, artist) url = reque(api_search_trk % song.replace("#", ""), chat_id, True).json() except AttributeError: return try: for a in range(url['total'] + 1): if url['data'][a]['title'] == track: ids = url['data'][a]['link'] image = url['data'][a]['album']['cover_xl'] break except IndexError: try: ids = "https://open.spotify.com/track/%s" % infos[ 'external_metadata']['spotify']['track']['id'] try: url = spo.track(ids) except: spo = Spotify(generate_token()) url = spo.track(ids) image = url['album']['images'][0]['url'] except KeyError: try: ids = api_track % infos['external_metadata']['deezer'][ 'track']['id'] try: url = reque(ids, chat_id, True).json() except AttributeError: return image = url['album']['cover_xl'] except KeyError: sendMessage(chat_id, "Sorry I can't detect the track :(") return keyboard = [[ InlineKeyboardButton(queries['download']['text'], callback_data=ids), InlineKeyboardButton(queries['info']['text'], callback_data=album) ]] sendPhoto(chat_id, image, caption="{} - {}".format(track, artist), reply_markup=InlineKeyboardMarkup(keyboard))
def warn(user: User, chat: Chat, reason: str, message: Message, warner: User = None) -> str: if is_user_admin(chat, user.id): message.reply_text("Damn admins, can't even be warned!") return "" if warner: warner_tag = mention_html(warner.id, warner.first_name) else: warner_tag = "Automated warn filter." limit, soft_warn = sql.get_warn_setting(chat.id) num_warns, reasons = sql.warn_user(user.id, chat.id, reason) if num_warns >= limit: sql.reset_warns(user.id, chat.id) if soft_warn: # kick chat.unban_member(user.id) reply = "{} warnings, {} has been kicked!".format( limit, mention_html(user.id, user.first_name)) else: # ban chat.kick_member(user.id) reply = "{} warnings, {} has been banned!".format( limit, mention_html(user.id, user.first_name)) for warn_reason in reasons: reply += "\n - {}".format(html.escape(warn_reason)) message.bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker keyboard = [] log_reason = "<b>{}:</b>" \ "\n#WARN_BAN" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {} (<code>{}</code>)" \ "\n<b>Reason:</b> {}"\ "\n<b>Counts:</b> <code>{}/{}</code>".format(html.escape(chat.title), warner_tag, mention_html(user.id, user.first_name), user.id, reason, num_warns, limit) else: keyboard = InlineKeyboardMarkup([[ InlineKeyboardButton("Remove warn (admin only)", callback_data="rm_warn({})".format(user.id)) ]]) reply = "{} <b>has been WARNED!</b> \nCount:{}/{}".format( mention_html(user.id, user.first_name), num_warns, limit) if reason: reply += "\nReason: {}".format(html.escape(reason)) log_reason = "<b>{}:</b>" \ "\n#WARN" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {} (<code>{}</code>)" \ "\n<b>Reason:</b> {}"\ "\n<b>Counts:</b> <code>{}/{}</code>".format(html.escape(chat.title), warner_tag, mention_html(user.id, user.first_name), user.id, reason, num_warns, limit) try: message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML, quote=False) else: raise return log_reason
def reply_filter(bot: Bot, update: Update): chat = update.effective_chat message = update.effective_message to_match = extract_text(message) if not to_match: return chat_filters = sql.get_chat_triggers(chat.id) for keyword in chat_filters: pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])" if re.search(pattern, to_match, flags=re.IGNORECASE): filt = sql.get_filter(chat.id, keyword) if filt.is_sticker: message.reply_sticker(filt.reply) elif filt.is_document: message.reply_document(filt.reply) elif filt.is_image: message.reply_photo(filt.reply) elif filt.is_audio: message.reply_audio(filt.reply) elif filt.is_voice: message.reply_voice(filt.reply) elif filt.is_video: message.reply_video(filt.reply) elif filt.has_markdown: buttons = sql.get_buttons(chat.id, filt.keyword) keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) try: message.reply_text( filt.reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=keyboard, ) except BadRequest as excp: if excp.message == "Unsupported url protocol": message.reply_text( "You seem to be trying to use an unsupported url protocol. Telegram " "doesn't support buttons for some protocols, such as tg://. Please try " "again, or ask in @YorktownEagleUnion for help." ) elif excp.message == "Reply message not found": bot.send_message( chat.id, filt.reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=keyboard, ) else: message.reply_text( "This note could not be sent, as it is incorrectly formatted. Ask in " "@YorktownEagleUnion if you can't figure out why!" ) LOGGER.warning( "Message %s could not be parsed", str(filt.reply) ) LOGGER.exception( "Could not parse filter %s in chat %s", str(filt.keyword), str(chat.id), ) else: # LEGACY - all new filters will have has_markdown set to True. message.reply_text(filt.reply) break
def DaisyX_about_callback(update, context): query = update.callback_query if query.data == "aboutmanu_": query.message.edit_text( text= f"*😍 Hi again! The name's {dispatcher.bot.first_name} 😍 \n\nAs You I'm a next generational group management bot developed by Infinity_Bots.* " f"\n\n 🔥 Join [Infinity_Bots](https://t.me/Infinity_Bots) To Keep Yourself Updated About {dispatcher.bot.first_name} 🔥" f"\n\n I have the normal GROUP MANAGING functions like flood control, a warning system etc but I mainly have the advanced and handy Antispam system and the SIBYL banning system which safegaurds and helps your group from spammers." f"\n\nI Can Manage Your Groups Smoothly, With Some Special Features [:)](https://telegra.ph/file/473cc17913393959e0667.jpg)" f"\n\n👇 You Can Know More About Me By Clicking The Below Buttons 👇", parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([ [ InlineKeyboardButton(text="How To Use Me", callback_data="aboutmanu_howto"), InlineKeyboardButton(text="T & C", callback_data="aboutmanu_tac"), ], [ InlineKeyboardButton(text="❔Help & Commands", callback_data="help_back") ], [ InlineKeyboardButton(text="Back", callback_data="aboutmanu_back") ], ]), ) elif query.data == "aboutmanu_back": query.message.edit_text( PM_START_TEXT, reply_markup=InlineKeyboardMarkup(buttons), parse_mode=ParseMode.MARKDOWN, timeout=60, ) elif query.data == "aboutmanu_howto": query.message.edit_text( text=f"* 「 BASIC HELP 」*" f"\nIf You Can Also Add {dispatcher.bot.first_name} To Your Chats By Clicking [Here](http://t.me/{dispatcher.bot.username}?startgroup=true) And Selecting Chat. \n" f"\n\nYou Can get support {dispatcher.bot.first_name} by joining [InfinityJE](https://t.me/infinityje).\n" f"", parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([ [ InlineKeyboardButton(text="Admins Settings", callback_data="aboutmanu_permis"), InlineKeyboardButton(text="Anti Spam", callback_data="aboutmanu_spamprot"), ], [ InlineKeyboardButton(text="Back", callback_data="aboutmanu_") ], ]), ) elif query.data == "aboutmanu_credit": query.message.edit_text( text= f"*{dispatcher.bot.first_name} Is the redisigned version of Daisy and Naruto for the best performance.*" f"\n\nBased on [Daisy](https://github.com/inukaasith/daisy) + [Naruto](https://github.com/imjanindu/narutorobot)." f"\n\n{dispatcher.bot.first_name}'s source code was written by InukaASiTH and Imjanindu" f"\n\nIf Any Question About {dispatcher.bot.first_name}, \nLet Us Know At @{SUPPORT_CHAT}.", parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text="Back", callback_data="aboutmanu_tac") ]]), ) elif query.data == "aboutmanu_permis": query.message.edit_text( text=f"<b> 「 Admin Permissions 」</b>" f"\nTo avoid slowing down, {dispatcher.bot.first_name} caches admin rights for each user. This cache lasts about 10 minutes; this may change in the future. This means that if you promote a user manually (without using the /promote command), {dispatcher.bot.first_name} will only find out ~10 minutes later." f"\n\nIF you want to update them immediately, you can use the /admincache command,thta'll force {dispatcher.bot.first_name} to check who the admins are again and their permissions" f"\n\nIf you are getting a message saying:" f"\n<Code>You must be this chat administrator to perform this action!</code>" f"\nThis has nothing to do with {dispatcher.bot.first_name}'s rights; this is all about YOUR permissions as an admin. {dispatcher.bot.first_name} respects admin permissions; if you do not have the Ban Users permission as a telegram admin, you won't be able to ban users with {dispatcher.bot.first_name}. Similarly, to change {dispatcher.bot.first_name} settings, you need to have the Change group info permission." f"\n\nThe message very clearly says that you need these rights - <i>not {dispatcher.bot.first_name}.</i>", parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text="Back", callback_data="aboutmanu_howto") ]]), ) elif query.data == "aboutmanu_spamprot": query.message.edit_text( text="* 「 Anti-Spam Settings 」*" "\n- /antispam <on/off/yes/no>: Change antispam security settings in the group, or return your current settings(when no arguments)." "\n_This helps protect you and your groups by removing spam flooders as quickly as possible._" "\n\n- /setflood <int/'no'/'off'>: enables or disables flood control" "\n- /setfloodmode <ban/kick/mute/tban/tmute> <value>: Action to perform when user have exceeded flood limit. ban/kick/mute/tmute/tban" "\n_Antiflood allows you to take action on users that send more than x messages in a row. Exceeding the set flood will result in restricting that user._" "\n\n- /addblacklist <triggers>: Add a trigger to the blacklist. Each line is considered one trigger, so using different lines will allow you to add multiple triggers." "\n- /blacklistmode <off/del/warn/ban/kick/mute/tban/tmute>: Action to perform when someone sends blacklisted words." "\n_Blacklists are used to stop certain triggers from being said in a group. Any time the trigger is mentioned, the message will immediately be deleted. A good combo is sometimes to pair this up with warn filters!_" "\n\n- /reports <on/off>: Change report setting, or view current status." "\n • If done in pm, toggles your status." "\n • If in chat, toggles that chat's status." "\n_If someone in your group thinks someone needs reporting, they now have an easy way to call all admins._" "\n\n- /lock <type>: Lock items of a certain type (not available in private)" "\n- /locktypes: Lists all possible locktypes" "\n_The locks module allows you to lock away some common items in the telegram world; the bot will automatically delete them!_" '\n\n- /addwarn <keyword> <reply message>: Sets a warning filter on a certain keyword. If you want your keyword to be a sentence, encompass it with quotes, as such: /addwarn "very angry" This is an angry user. ' "\n- /warn <userhandle>: Warns a user. After 3 warns, the user will be banned from the group. Can also be used as a reply." "\n- /strongwarn <on/yes/off/no>: If set to on, exceeding the warn limit will result in a ban. Else, will just kick." "\n_If you're looking for a way to automatically warn users when they say certain things, use the /addwarn command._" "\n\n- /welcomemute <off/soft/strong>: All users that join, get muted" "\n_ A button gets added to the welcome message for them to unmute themselves. This proves they aren't a bot! soft - restricts users ability to post media for 24 hours. strong - mutes on join until they prove they're not bots._", parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text="Back", callback_data="aboutmanu_howto") ]]), ) elif query.data == "aboutmanu_tac": query.message.edit_text( text=f"<b> 「 Terms and Conditions 」</b>\n" f"\n<i>To Use This Bot, You Need To Read Terms and Conditions Carefully.</i>\n" f"\n✪ We always respect your privacy \n We never log into bot's api and spying on you \n We use a encripted database \n Bot will automatically stops if someone logged in with api." f"\n✪ Always try to keep credits, so \n This hardwork is done by Infinity_Bots team spending many sleepless nights.. So, Respect it." f"\n✪ Some modules in this bot is owned by different authors, So, \n All credits goes to them \n Also for <b>Paul Larson for Marie</b>." f"\n✪ If you need to ask anything about \n this bot, Go @{SUPPORT_CHAT}." f"\n✪ If you asking nonsense in Support \n Chat, you will get warned/banned." f"\n✪ All api's we used owned by originnal authors \n Some api's we use Free version \n Please don't overuse AI Chat." f"\n✪ We don't Provide any support to forks,\n So these terms and conditions not applied to forks \n If you are using a fork of DaisyXBot we are not resposible for anything." f"\n\nFor any kind of help, related to this bot, Join @{SUPPORT_CHAT}." f"\n\n<i>Terms & Conditions will be changed anytime</i>\n", parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text="Credits", callback_data="aboutmanu_credit"), InlineKeyboardButton(text="Back", callback_data="aboutmanu_"), ]]), )