def admin_prize(message): if len(message.text.split()) > 1 and message.text.split()[1] == tokens.my_prize: all_imgs = os.listdir(config.prize_dir) rand_file = random.choice(all_imgs) your_file = open(config.prize_dir + rand_file, "rb") if rand_file.endswith(".gif"): my_bot.send_document(message.chat.id, your_file, reply_to_message_id=message.message_id) else: my_bot.send_photo(message.chat.id, your_file, reply_to_message_id=message.message_id) your_file.close() user_action_log(message, "got that prize:\n{0}".format(your_file.name))
def wolfram_solver(message): """ обрабатывает запрос и посылает пользователю картинку с результатом в случае удачи :param message: :return: """ # сканируем и передаём всё, что ввёл пользователь после '/wolfram ' или '/wf ' if not len(message.text.split()) == 1: my_bot.send_chat_action(message.chat.id, 'upload_photo') your_query = ' '.join(message.text.split()[1:]) user_action_log( message, "entered this query for /wolfram:\n{0}".format(your_query)) response = requests.get( "https://api.wolframalpha.com/v1/simple?appid=" + tokens.wolfram, params={'i': your_query}) # если всё хорошо, и запрос найден if response.status_code == 200: img_original = Image.open(io.BytesIO(response.content)) img_cropped = img_original.crop( (0, 95, 540, img_original.size[1] - 50)) io_img = io.BytesIO() io_img.name = "wolfram {}.png".format(your_query.replace("/", "_")) img_cropped.save(io_img, format="png") io_img.seek(0) wolfram_max_ratio = 2.5 if img_cropped.size[1] / img_cropped.size[0] > wolfram_max_ratio: my_bot.send_document(message.chat.id, io_img, reply_to_message_id=message.message_id) else: my_bot.send_photo(message.chat.id, io_img, reply_to_message_id=message.message_id) user_action_log( message, "has received this Wolfram output:\n{0}".format(response.url)) # если всё плохо else: my_bot.reply_to( message, "Запрос не найдён.\nЕсли ты ввёл его на русском, " "то попробуй ввести его на английском.") user_action_log(message, "didn't received any data") # если пользователь вызвал /wolfram без аргумента else: my_bot.reply_to( message, "Использование: `/wolfram <запрос>` или `/wf <запрос>`", parse_mode="Markdown") user_action_log(message, "called /wolfram without any arguments")
def send_post(self, destination): # Отправляем текст, нарезая при необходимости for text in cut_long_text(self.final_text): my_bot.send_message( destination, text, parse_mode="HTML", disable_web_page_preview=self.web_preview_url == '') # Отправляем отображаемые приложения к посту for url in self.video_links: my_bot.send_message(destination, url) for url in self.gif_links: my_bot.send_document(destination, url) for url in self.image_links: my_bot.send_photo(destination, url) for url in self.audio_links: my_bot.send_audio(destination, url)
def wolfram_solver(message): """ обрабатывает запрос и посылает пользователю картинку с результатом в случае удачи :param message: :return: """ # сканируем и передаём всё, что ввёл пользователь после '/wolfram ' или '/wf ' if not len(message.text.split()) == 1: my_bot.send_chat_action(message.chat.id, 'upload_photo') your_query = ' '.join(message.text.split()[1:]) user_action_log(message, "entered this query for /wolfram:\n{0}".format(your_query)) response = requests.get("https://api.wolframalpha.com/v1/simple?appid=" + tokens.wolfram, params={'i': your_query}) # если всё хорошо, и запрос найден if response.status_code == 200: img_original = Image.open(io.BytesIO(response.content)) img_cropped = img_original.crop((0, 95, 540, img_original.size[1] - 50)) io_img = io.BytesIO() io_img.name = "wolfram {}.png".format(your_query.replace("/", "_")) img_cropped.save(io_img, format="png") io_img.seek(0) wolfram_max_ratio = 2.5 if img_cropped.size[1] / img_cropped.size[0] > wolfram_max_ratio: my_bot.send_document(message.chat.id, io_img, reply_to_message_id=message.message_id) else: my_bot.send_photo(message.chat.id, io_img, reply_to_message_id=message.message_id) user_action_log(message, "has received this Wolfram output:\n{0}".format(response.url)) # если всё плохо else: my_bot.reply_to(message, "Запрос не найдён.\nЕсли ты ввёл его на русском, " "то попробуй ввести его на английском.") user_action_log(message, "didn't received any data") # если пользователь вызвал /wolfram без аргумента else: my_bot.reply_to(message, "Использование: `/wolfram <запрос>` или `/wf <запрос>`", parse_mode="Markdown") user_action_log(message, "called /wolfram without any arguments")
def rand_image_maths(message): path = config.math_dir subjects = ["algebra", "calculus", "funcan"] user_action_log(message, "asked for maths") if not len(message.text.split()) == 1: your_subject = message.text.split()[1].lower() if your_subject in subjects: all_imgs = os.listdir(path) rand_img = random.choice(all_imgs) while not rand_img.startswith(your_subject): rand_img = random.choice(all_imgs) your_img = open(path + rand_img, "rb") my_bot.send_photo(message.chat.id, your_img, reply_to_message_id=message.message_id) user_action_log( message, "chose subject '{0}' " "and got that image:\n" "{1}".format(your_subject, your_img.name)) your_img.close() else: my_bot.reply_to( message, "На данный момент доступны факты" " только по следующим предметам:\n{0}\n" "Выбираю рандомный факт:".format(subjects)) all_imgs = os.listdir(path) rand_img = random.choice(all_imgs) your_img = open(path + rand_img, "rb") my_bot.send_photo(message.chat.id, your_img, reply_to_message_id=message.message_id) user_action_log( message, "chose a non-existent subject '{0}' " "and got that image:\n" "{1}".format(your_subject, your_img.name)) your_img.close() else: all_imgs = os.listdir(path) rand_img = random.choice(all_imgs) your_img = open(path + rand_img, "rb") my_bot.send_photo(message.chat.id, your_img, reply_to_message_id=message.message_id) user_action_log(message, "got that image:\n{0}".format(your_img.name)) your_img.close()
def rand_image_task(message): path = config.task_dir difficulty = ["1", "2", "3"] user_action_log(message, "asked for a challenge") if not len(message.text.split()) == 1: your_difficulty = message.text.split()[1] if your_difficulty in difficulty: all_imgs = os.listdir(path) rand_img = random.choice(all_imgs) while not rand_img.startswith(your_difficulty): rand_img = random.choice(all_imgs) your_img = open(path + rand_img, "rb") my_bot.send_photo(message.chat.id, your_img, reply_to_message_id=message.message_id) user_action_log( message, "chose a difficulty level '{0}' " "and got that image:\n{1}".format(your_difficulty, your_img.name)) your_img.close() else: my_bot.reply_to( message, "Доступно только три уровня сложности:\n" "{0}" "\nВыбираю рандомную задачу:".format(difficulty)) all_imgs = os.listdir(path) rand_img = random.choice(all_imgs) your_img = open(path + rand_img, "rb") my_bot.send_photo(message.chat.id, your_img, reply_to_message_id=message.message_id) user_action_log( message, "chose a non-existent difficulty level '{0}' " "and got that image:\n{1}".format(your_difficulty, your_img.name)) your_img.close() else: all_imgs = os.listdir(path) rand_img = random.choice(all_imgs) your_img = open(path + rand_img, "rb") my_bot.send_photo(message.chat.id, your_img, reply_to_message_id=message.message_id) user_action_log(message, "got that image:\n{0}".format(your_img.name)) your_img.close()
def rand_image_maths(message): path = config.math_dir subjects = ["algebra", "calculus", "funcan"] user_action_log(message, "asked for maths") if not len(message.text.split()) == 1: your_subject = message.text.split()[1].lower() if your_subject in subjects: all_imgs = os.listdir(path) rand_img = random.choice(all_imgs) while not rand_img.startswith(your_subject): rand_img = random.choice(all_imgs) your_img = open(path + rand_img, "rb") my_bot.send_photo(message.chat.id, your_img, reply_to_message_id=message.message_id) user_action_log(message, "chose subject '{0}' " "and got that image:\n" "{1}".format(your_subject, your_img.name)) your_img.close() else: my_bot.reply_to(message, "На данный момент доступны факты" " только по следующим предметам:\n{0}\n" "Выбираю рандомный факт:".format(subjects) ) all_imgs = os.listdir(path) rand_img = random.choice(all_imgs) your_img = open(path + rand_img, "rb") my_bot.send_photo(message.chat.id, your_img, reply_to_message_id=message.message_id) user_action_log(message, "chose a non-existent subject '{0}' " "and got that image:\n" "{1}".format(your_subject, your_img.name)) your_img.close() else: all_imgs = os.listdir(path) rand_img = random.choice(all_imgs) your_img = open(path + rand_img, "rb") my_bot.send_photo(message.chat.id, your_img, reply_to_message_id=message.message_id) user_action_log(message, "got that image:\n{0}".format(your_img.name)) your_img.close()
def rand_image_task(message): path = config.task_dir difficulty = ["1", "2", "3"] user_action_log(message, "asked for a challenge") if not len(message.text.split()) == 1: your_difficulty = message.text.split()[1] if your_difficulty in difficulty: all_imgs = os.listdir(path) rand_img = random.choice(all_imgs) while not rand_img.startswith(your_difficulty): rand_img = random.choice(all_imgs) your_img = open(path + rand_img, "rb") my_bot.send_photo(message.chat.id, your_img, reply_to_message_id=message.message_id) user_action_log(message, "chose a difficulty level '{0}' " "and got that image:\n{1}".format(your_difficulty, your_img.name)) your_img.close() else: my_bot.reply_to(message, "Доступно только три уровня сложности:\n" "{0}" "\nВыбираю рандомную задачу:".format(difficulty)) all_imgs = os.listdir(path) rand_img = random.choice(all_imgs) your_img = open(path + rand_img, "rb") my_bot.send_photo(message.chat.id, your_img, reply_to_message_id=message.message_id) user_action_log(message, "chose a non-existent difficulty level '{0}' " "and got that image:\n{1}".format(your_difficulty, your_img.name)) your_img.close() else: all_imgs = os.listdir(path) rand_img = random.choice(all_imgs) your_img = open(path + rand_img, "rb") my_bot.send_photo(message.chat.id, your_img, reply_to_message_id=message.message_id) user_action_log(message, "got that image:\n{0}".format(your_img.name)) your_img.close()
def my_kek(message): """ открывает соответствующие файл и папку, кидает рандомную строчку из файла, или рандомную картинку или гифку из папки :param message: :return: """ if not hasattr(my_kek, "kek_bang"): my_kek.kek_bang = time.time() if not hasattr(my_kek, "kek_crunch"): my_kek.kek_crunch = my_kek.kek_bang + 60 * 60 if not hasattr(my_kek, "kek_enable"): my_kek.kek_enable = True if not hasattr(my_kek, "kek_counter"): my_kek.kek_counter = 0 if not hasattr(weather.my_weather, "weather_bold"): weather.my_weather.weather_bold = False kek_init = True user_action_log(message, "asked for kek") if message.chat.id == int(config.mm_chat): if my_kek.kek_counter == 0: my_kek.kek_bang = time.time() my_kek.kek_crunch = my_kek.kek_bang + 60 * 60 my_kek.kek_counter += 1 kek_init = True elif (my_kek.kek_counter >= config.limit_kek and time.time() <= my_kek.kek_crunch): kek_init = False elif time.time() > my_kek.kek_crunch: my_kek.kek_counter = -1 kek_init = True flood_count(message) if not (kek_init and my_kek.kek_enable): return if message.chat.id == config.mm_chat: my_kek.kek_counter += 1 your_destiny = random.randint(1, 30) # если при вызове не повезло, то кикаем из чата if your_destiny == 13 and str(message.chat.id) == config.mm_chat: user_action_log(message, "is unlucky and got banhammer kek") my_bot.reply_to(message, "Предупреждал же, что кикну. " "Если не предупреждал, то ") my_bot.send_document(message.chat.id, config.gif_links[0], reply_to_message_id=message.message_id) try: if int(message.from_user.id) in config.admin_ids: my_bot.reply_to(message, "... Но против хозяев не восстану.") user_action_log(message, "can't be kicked out") else: # кикаем кекуна из чата (можно ещё добавить условие, что если один юзер прокекал больше числа n # за время t, то тоже в бан) release_time = ro_roll( "Эй, {}.\n".format( message.from_user.first_name) + "Твой /kek обеспечил тебе {} мин. бана. Поздравляю!", chat_id=message.chat.id, max_time=15) user_action_log(message, "sleeping before ban") time.sleep(5) my_bot.kick_chat_member(message.chat.id, message.from_user.id, until_date=release_time) user_action_log(message, "has been kicked out until {}".format(release_time)) except Exception as ex: logging.exception(ex) pass else: type_of_kek = random.randint(1, 33) # 1/33 шанс на картинку или гифку if type_of_kek == 9: all_imgs = os.listdir(config.kek_dir) rand_file = random.choice(all_imgs) your_file = open(config.kek_dir + rand_file, "rb") if rand_file.endswith(".gif"): my_bot.send_document(message.chat.id, your_file, reply_to_message_id=message.message_id) else: my_bot.send_photo(message.chat.id, your_file, reply_to_message_id=message.message_id) your_file.close() user_action_log(message, "got that kek:\n{0}".format(your_file.name)) elif type_of_kek == 10: my_bot.send_document(message.chat.id, random.choice(config.gif_links), reply_to_message_id=message.message_id) elif type_of_kek < 10: file_kek = open(config.file_location['kek_file_ids'], 'r', encoding='utf-8') # while your_kek == '\n': your_kek = random.choice(file_kek.readlines()) # если попалась строчка вида '<sticker>ID', то шлём стикер по ID if str(your_kek).startswith("<sticker>"): sticker_id = str(your_kek[9:]).strip() my_bot.send_sticker(message.chat.id, sticker_id, reply_to_message_id=message.message_id) # если попалась строчка вида '<audio>ID', то шлём аудио по ID elif str(your_kek).startswith("<audio>"): audio_id = str(your_kek[7:]).strip() my_bot.send_audio(message.chat.id, audio_id, reply_to_message_id=message.message_id) # если попалась строчка вида '<voice>ID', то шлём голосовое сообщение по ID elif str(your_kek).startswith("<voice>"): voice_id = str(your_kek[7:]).strip() my_bot.send_voice(message.chat.id, voice_id, reply_to_message_id=message.message_id) user_action_log(message, "got that kek:\n{0}".format(str(your_kek).replace("<br>", "\n")[:35])) # иначе смотрим файл else: your_kek = '' file_kek = open(config.file_location['/kek'], 'r', encoding='utf-8') while your_kek == '': your_kek = random.choice(file_kek.readlines()) my_bot.reply_to(message, str(your_kek).replace("<br>", "\n")) file_kek.close() user_action_log(message, "got that kek:\n{0}".format(str(your_kek).replace("<br>", "\n")[:35])) if my_kek.kek_counter == config.limit_kek - 10: time_remaining = divmod(int(my_kek.kek_crunch) - int(time.time()), 60) my_bot.reply_to(message, "<b>Внимание!</b>\nЭтот чат может покекать " "ещё не более {0} раз до истечения кекочаса " "(через {1} мин. {2} сек.).\n" "По истечению кекочаса " "счётчик благополучно сбросится.".format(config.limit_kek - my_kek.kek_counter, time_remaining[0], time_remaining[1]), parse_mode="HTML") if my_kek.kek_counter == config.limit_kek - 1: time_remaining = divmod(int(my_kek.kek_crunch) - int(time.time()), 60) my_bot.reply_to(message, "<b>EL-FIN!</b>\n" "Теперь вы сможете кекать " "только через {0} мин. {1} сек.".format(time_remaining[0], time_remaining[1]), parse_mode="HTML") my_kek.kek_counter += 1