def disa(message): if not hasattr(disa, "disa_first"): disa.disa_first = True if not hasattr(disa, "disa_bang"): disa.disa_bang = time.time() if not hasattr(disa, "disa_crunch"): disa.disa_crunch = disa.disa_bang + 60 * 60 disa_init = False # пытаемся открыть файл с количеством Дисиных хромосом disa_chromo = value_from_file(config.file_location['chromo'], 46) disa_chromo += 1 value_to_file(config.file_location['chromo'], disa_chromo) user_action_log(message, "added chromosome to Disa") if message.chat.type == "supergroup": if disa.disa_first: disa.disa_bang = time.time() disa.disa_crunch = disa.disa_bang + 60 * 60 disa.disa_first = False elif (not disa.disa_first) and (time.time() >= disa.disa_crunch): disa_init = True # запись счетчика в вк if disa_init and False: disa_vk_report(disa_chromo, message)
def build_child(message): s = current_controller.print_path(message.from_user) keyboard = types.ReplyKeyboardMarkup() # s.sort() if current_controller.can_get_back(message) is False: keyboard.row('1', '2', '3') keyboard.row('4', '5', '6') keyboard.row('7', '8', '9') else: kook = False for name in s: if name != '.DS_Store' and name != 'main.txt': kook = True # keyboard.add(types.KeyboardButton(name)) if kook: keyboard.row('Да', 'Нет') # print(current_controller.print_path(message.from_user)) # newpath = current_controller.other_get_file_name(message) # newpath = newpath + '/kek' # if not os.path.exists(newpath): os.makedirs(newpath) if current_controller.can_get_back(message): back = types.KeyboardButton('Назад') keyboard.row(back) if current_controller.can_get_back(message): back = types.KeyboardButton('В начало') keyboard.row(back) news = current_controller.other_get_file_name(message) my_file = open(news + '/' + 'main.txt', encoding='utf-8') my_string = my_file.read() msg = bot.send_message(message.chat.id, my_string, reply_markup=keyboard) user_action_log(message, 'now in ' + news) bot.register_next_step_handler(msg, where)
def my_d6(message): """ рандомно выбирает элементы из списка значков TODO: желательно найти способ их увеличить или заменить на ASCII арт :param message: :return: """ d6 = ["⚀", "⚁", "⚂", "⚃", "⚄", "⚅"] dice = 2 roll_sum = 0 symbols = '' for _ in str(message.text).lower().split(): if not len(message.text.split()) == 1: try: dice = int(message.text.split()[1]) except ValueError: my_bot.reply_to(message, "Не понял число костей. " "Пожалуйста, введи команду " "в виде \'/d6 <int>\', " "где <int> — целое от 1 до 10.") return if 0 < dice <= 10: max_result = dice * 6 for count in range(dice): roll_index = random.randint(0, len(d6) - 1) roll_sum += roll_index + 1 if count < dice - 1: symbols += '{0} + '.format(d6[roll_index]) elif count == dice - 1: symbols += '{0} = {1} ({2})'.format(d6[roll_index], roll_sum, max_result) my_bot.reply_to(message, symbols) user_action_log(message, "got that D6 output: {0}".format(symbols))
def add_kek(message): add_id = '' your_new_kek = '' if getattr(message, 'reply_to_message') is not None: # msg_media = first((getattr(message.reply_to_message, 'sticker'), # getattr(message.reply_to_message, 'audio'), # getattr(message.reply_to_message, 'voice')), key=lambda x: x is not None) if getattr(message.reply_to_message, 'sticker') is not None: add_id = '<sticker>{}'.format( message.reply_to_message.sticker.file_id) elif getattr(message.reply_to_message, 'audio') is not None: add_id = '<audio>{}'.format(message.reply_to_message.audio.file_id) elif getattr(message.reply_to_message, 'voice') is not None: add_id = '<voice>{}'.format(message.reply_to_message.voice.file_id) elif getattr(message.reply_to_message, 'text') is not None: add_id = message.reply_to_message.text else: return with open(config.file_location['kek_requests'], 'a') as add_ids: add_ids.write('\n{}'.format(add_id)) elif len(message.text.split()) > 1: your_new_kek = ' '.join(message.text.split()[1:]) with open(config.file_location['kek_requests'], 'a') as add_keks: add_keks.write('\n{}'.format(your_new_kek)) user_action_log(message, "requested a kek:\n{0}{1}".format(add_id, your_new_kek))
def my_dn(message): roll_sum = 0 symbols = '' if len(message.text.split()) == 3: try: dice_max = int(message.text.split()[1]) dice_n = int(message.text.split()[2]) except ValueError: return max_result = dice_n * dice_max for count in range(dice_n): try: roll = random.randint(0, dice_max) roll_sum += roll if count < dice_n - 1: symbols += '{0} + '.format(roll) elif count == dice_n - 1: symbols += '{0} = {1} ({2})'.format(roll, roll_sum, max_result) except ValueError: pass if not len(symbols) > 4096: my_bot.reply_to(message, symbols) user_action_log(message, "knew about /dn and got that output: {0}".format(symbols)) else: my_bot.reply_to(message, "Слишком большие числа. " "Попробуй что-нибудь поменьше") user_action_log(message, "knew about /dn " "and the answer was too long " "to fit one message")
async def my_dn(message): roll_sum = 0 symbols = '' if len(message.text.split()) == 3: try: dice_max = int(message.text.split()[1]) dice_n = int(message.text.split()[2]) except ValueError: return max_result = dice_n * dice_max for count in range(dice_n): try: roll = random.randint(0, dice_max) roll_sum += roll if count < dice_n - 1: symbols += '{0} + '.format(roll) elif count == dice_n - 1: symbols += '{0} = {1} ({2})'.format( roll, roll_sum, max_result) except ValueError: pass if not len(symbols) > 4096: await message.reply(symbols) user_action_log( message, "knew about /dn and got that output: {0}".format(symbols)) else: message.reply("Слишком большие числа. " "Попробуй что-нибудь поменьше") user_action_log( message, "knew about /dn " "and the answer was too long " "to fit one message")
def me_message(message): # В ЛС бот не может удалять сообщения пользователя try: my_bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) except Exception: logging.exception("message") # Если у пользователя есть юзернэйм, то берём его как your_name if message.from_user.username is not None: your_name = '[@{}](tg://user?id={})'.format(message.from_user.username, message.from_user.id) # Иначе, берём имя пользователя, которое есть всегда else: your_name = '[{}](tg://user?id={})'.format(message.from_user.first_name, message.from_user.id) # Если /me непусто, берём всё, что после '/me ' if len(message.text.split()) < 2: return your_message = message.text.split(maxsplit=1)[1] your_me = "{} {}".format(your_name, your_message) try: # Если /me было ответом на какое-то сообщение, то посылаем запрос как ответ # TODO: расширить эту фичу на все команды if getattr(message, 'reply_to_message') is not None: my_bot.send_message(message.chat.id, your_me, parse_mode="Markdown", disable_notification=True, reply_to_message_id=message.reply_to_message.message_id) else: my_bot.send_message(message.chat.id, your_me, parse_mode="Markdown", disable_notification=True) except Exception: logging.exception("message") user_action_log(message, "called the me:\n{}".format(your_me))
def arxiv_search(query, message): try: arxiv_search_res = arxiv.query(search_query=query, max_results=3) query_answer = '' for paper in arxiv_search_res: end = '…' if len(paper['summary']) > 251 else '' a_name = paper['authors'][0] if len(paper['authors']) > 1: a_name += 'et al.' query_answer += \ '• {0}. <a href="{1}">{2}</a>. {3}{4}\n'.format( a_name, paper['arxiv_url'], escape(paper['title'].replace('\n', ' ')), escape(paper['summary'][0:250].replace('\n', ' ')), end) print(query_answer) user_action_log(message, "called arxiv search with query {}".format(query)) my_bot.reply_to(message, query_answer, parse_mode="HTML") except Exception as ex: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] action_log("Unknown Exception:\n{}: {}\nat {} line {}\n" "Creating the alert file.".format(exc_type, ex, fname, exc_tb.tb_lineno))
def vk_post(message): if len(message.text.split()) > 1: post_id = message.text.split('wall')[-1] user_action_log(message, "has requested vk post: {}".format(post_id)) response = requests.get('https://api.vk.com/method/wall.getById', params={ 'access_token': tokens.vk, 'posts': post_id, 'extended': '1', 'v': '5.68' }) response_list = response.json()['response']['items'] if len(response_list) == 0: my_bot.reply_to( message, "Неудача! Использование: `/vk_post vk.com/wall-51776562_939`", parse_mode="Markdown") return post = vk_utils.VkPost(response_list[0]) post.prepare_post() post.send_post(message.chat.id) else: my_bot.reply_to(message, "Использование: `/vk_post vk.com/wall-51776562_939`", parse_mode="Markdown")
async def my_d6(message): """ рандомно выбирает элементы из списка значков TODO: желательно найти способ их увеличить или заменить на ASCII арт :param message: :return: """ d6 = ["⚀", "⚁", "⚂", "⚃", "⚄", "⚅"] dice = 2 roll_sum = 0 symbols = '' for _ in str(message.text).lower().split(): if not len(message.text.split()) == 1: try: dice = int(message.text.split()[1]) except ValueError: await message.reply("Не понял число костей. " "Пожалуйста, введи команду " "в виде \'/d6 <int>\', " "где <int> — целое от 1 до 10.") return if 0 < dice <= 10: max_result = dice * 6 for count in range(dice): roll_index = random.randint(0, len(d6) - 1) roll_sum += roll_index + 1 if count < dice - 1: symbols += '{0} + '.format(d6[roll_index]) elif count == dice - 1: symbols += '{0} = {1} ({2})'.format(d6[roll_index], roll_sum, max_result) await message.reply(symbols) user_action_log(message, "got that D6 output: {0}".format(symbols))
def admin_post(message): if len(message.text.split()) > 1: global_lock.acquire() if message.text.split()[1] == "edit": try: with open(config.file_location_lastbotpost, 'r', encoding='utf-8') as file: last_msg_id = int(file.read()) my_edited_message = ' '.join(message.text.split()[2:]) my_bot.edit_message_text(my_edited_message, config.my_chatID, last_msg_id, parse_mode="Markdown") user_action_log( message, "has edited message {}:\n{}".format( last_msg_id, my_edited_message)) except (IOError, OSError): my_bot.reply_to(message, "Мне нечего редактировать.") else: my_message = ' '.join(message.text.split()[1:]) sent_message = my_bot.send_message(config.my_chatID, my_message, parse_mode="Markdown") with open(config.file_location_lastbotpost, 'w', encoding='utf-8') as file_lastmsgID_write: file_lastmsgID_write.write(str(sent_message.message_id)) user_action_log(message, "has posted this message:\n{}".format(my_message)) global_lock.release() else: my_bot.reply_to(message, "Мне нечего постить.")
def my_truth(message): answers = [ "да", "нет", "это не важно", "да, хотя зря", "никогда", "100%", "1 из 100" ] truth = random.choice(answers) my_bot.reply_to(message, truth) user_action_log(message, "has discovered the Truth:\n{0}".format(truth))
def update_bot(message): if not hasattr(update_bot, "check_sure"): update_bot.check_sure = True return my_bot.reply_to(message, "Ух, ухожу на обновление...") user_action_log(message, "remotely ran update script.") os.execl('/bin/bash', 'bash', 'bot_update.sh')
async def rules_command(message): if str(message.chat.id) == config.mm_chat: with open(config.file_location['/rules'], 'r', encoding='utf-8') as file: await message.reply(file.read(), parse_mode="HTML", disable_web_page_preview=True) user_action_log(message, "called rules")
def your_gender(message): with open(config.file_location['/gender'], 'r', encoding='utf-8') as file_gender: gender = random.choice(file_gender.readlines()) my_bot.reply_to(message, gender) user_action_log( message, "has discovered his gender:\n{0}".format( str(gender).replace("<br>", "\n")))
def kill_bot(message): if not hasattr(kill_bot, "check_sure"): kill_bot.check_sure = True return value_to_file(config.file_location['bot_killed'], 1) my_bot.send_document(message.chat.id, "https://t.me/mechmath/169445", caption="Ухожу на отдых!", reply_to_message_id=message.message_id) user_action_log(message, "remotely killed bot.") os._exit(0)
async def my_new_data(message): command = message.text.lower().split()[0] command_raw = re.split("@+", command)[0] with open(config.file_location[command_raw], 'r', encoding='utf-8') as file: await message.reply(file.read(), parse_mode="HTML", disable_web_page_preview=True) user_action_log(message, "called that command: {}".format(command))
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 anti_disa(message): global_lock.acquire() try: with open(config.file_location_disa, 'r', encoding='utf-8') as file_disa_read: disa_chromo = int(file_disa_read.read()) except (IOError, OSError, ValueError): disa_chromo = 46 pass disa_chromo -= 1 with open(config.file_location_disa, 'w', encoding='utf-8') as file_disa_write: file_disa_write.write(str(disa_chromo)) global_lock.release() user_action_log(message, "removed chromosome to Disa")
def vk_post(message): if len(message.text.split()) > 1: post_id = message.text.split('wall')[-1] user_action_log(message, "has requested vk post: {}".format(post_id)) response = requests.get('https://api.vk.com/method/wall.getById', params={'access_token': tokens.vk, 'posts': post_id, 'extended': '1', 'v': config.vk_ver}) response_list = response.json()['response']['items'] if len(response_list) == 0: my_bot.reply_to(message, "Неудача! Использование: `/vk vk.com/wall-51776562_939`", parse_mode="Markdown") return post = vk_utils.VkPost(response_list[0]) post.prepare_post() post.send_post(message.chat.id) else: my_bot.reply_to(message, "Использование: `/vk vk.com/wall-51776562_939`", parse_mode="Markdown")
def admin_clean(message): if not hasattr(admin_clean, "allow_long"): admin_clean.allow_long = False if not hasattr(admin_clean, "allow_long_id"): admin_clean.allow_long_id = -1 if len(message.text.split()) == 1: if admin_clean.allow_long: user_action_log(message, "cancelled big cleanup") admin_clean.allow_long = False return else: num_str = message.text.split()[1] if not num_str.isdigit(): if admin_clean.allow_long: user_action_log(message, "cancelled big cleanup") admin_clean.allow_long = False return num = int(num_str) allow_long_str = 'Long cleanup is allowed' if admin_clean.allow_long else 'Long cleanup is not allowed' user_action_log( message, "has launched cleanup of {} messages. {}".format(num, allow_long_str)) if num > 500: my_bot.reply_to( message, "Тааак, падажжи, слишком большое число указал, больше 500 не принимаю" ) return if num > 128 and (not admin_clean.allow_long or admin_clean.allow_long_id != message.from_user.id): my_bot.reply_to( message, "Вы запросили очистку более 128 сообщений. Для подтверждения отправьте " "команду еще раз. Для отмены отправльте команду с текстовым параметром. " "С уважением, ваш раб") admin_clean.allow_long = True admin_clean.allow_long_id = message.from_user.id return count = 0 msg_id = message.message_id while count < num: try: my_bot.delete_message(chat_id=message.chat.id, message_id=msg_id) count += 1 except: pass msg_id -= 1 user_action_log(message, "cleaned up {} messages".format(count))
def update_bot(message): if not hasattr(update_bot, "check_sure"): update_bot.check_sure = True return global_lock.acquire() try: file_update_write = open(config.bot_update_filename, 'w', encoding='utf-8') file_update_write.close() except RuntimeError: pass global_lock.release() my_bot.reply_to(message, "Ух, ухожу на обновление...") user_action_log(message, "remotely ran update script.") os.execl('/bin/bash', 'bash', 'bot_update.sh')
def command_or(message): user_action_log(message, "called: " + message.text) # Shitcode alert! or_lang = "ru" if len(message.text.split()) < 4: return or_message = message.text.split(' ', 1)[1] if "or" in message.text.split(): make_choice = re.split(r'[ ](?:or)[, ]', or_message) or_lang = "en" else: make_choice = re.split(r'[ ](?:или)[, ]', or_message) if len(make_choice) > 1 and not ((message.text.split()[1] == "или") or (message.text.split()[1] == "or")): choosen_answer = random.choice(make_choice) if or_lang == "ru": choosen_answer = re.sub(r'(?i)\bя\b', 'ты', choosen_answer) else: choosen_answer = re.sub(r'(?i)\bi\b', 'you', choosen_answer) # more subs to come my_bot.reply_to(message, choosen_answer)
def kill_bot(message): if not hasattr(kill_bot, "check_sure"): kill_bot.check_sure = True return global_lock.acquire() try: file_killed_write = open(config.bot_killed_filename, 'w', encoding='utf-8') file_killed_write.close() except RuntimeError: pass global_lock.release() my_bot.send_document(message.chat.id, "https://t.me/mechmath/169445", caption="Ухожу на отдых!", reply_to_message_id=message.message_id) user_action_log(message, "remotely killed bot.") os._exit(0)
async def command_or(message): user_action_log(message, 'called: ' + message.text) # Shitcode alert! or_lang = 'ru' if len(message.text.split()) < 4: return or_message = message.text.split(' ', 1)[1] if 'or' in message.text.split(): make_choice = re.split(r'[ ](?:or)[, ]', or_message) or_lang = 'en' else: make_choice = re.split(r'[ ](?:или)[, ]', or_message) if len(make_choice) > 1 and not ((message.text.split()[1] == 'или') or (message.text.split()[1] == 'or')): choosen_answer = random.choice(make_choice) if or_lang == 'ru': choosen_answer = re.sub(r'(?i)\bя\b', 'ты', choosen_answer) else: choosen_answer = re.sub(r'(?i)\bi\b', 'you', choosen_answer) # more subs to come await message.reply(choosen_answer)
def command_or(message): user_action_log(message, "called: " + message.text) # Shitcode alert! or_lang = "ru" if len(message.text.split()) < 4: return or_message = message.text.split(' ', 1)[1] if "or" in message.text.split(): make_choice = re.split(r'[ ](?:or)[, ]', or_message) or_lang = "en" else: make_choice = re.split(r'[ ](?:или)[, ]', or_message) if len(make_choice) > 1 and not ((message.text.split()[1] == "или") or (message.text.split()[1] == "or")): choosen_answer = random.choice(make_choice) if or_lang == "ru": choosen_answer = re.sub(r'(?i)\bя\b', 'ты', choosen_answer) else: choosen_answer = re.sub(r'(?i)\bi\b', 'you', choosen_answer) ## more subs to come my_bot.reply_to(message, choosen_answer)
async def arxiv_random(message): user_action_log(message, "made arxiv random query") try: eastern = pytz.timezone('US/Eastern') eastern_time = datetime.datetime.now(eastern) # publications on 20:00 if eastern_time.hour < 20: eastern_time -= datetime.timedelta(days=1) # no publications on friday and saturday if eastern_time.weekday() == 5: eastern_time -= datetime.timedelta(days=2) elif eastern_time.weekday() == 4: eastern_time -= datetime.timedelta(days=1) last_published_date = eastern_time.strftime("%Y-%m-%d") response = requests.get('http://export.arxiv.org/oai2', params={'verb': 'ListIdentifiers', 'set': 'math', 'metadataPrefix': 'oai_dc', 'from': last_published_date}) action_log("Random arxiv paper since {}".format(last_published_date)) # если всё хорошо if response.status_code == 200: response_tree = ElementTree.fromstring(response.content) num_of_papers = len(response_tree[2]) paper_index = random.randint(0, num_of_papers) paper_arxiv_id = response_tree[2][paper_index][0].text.split(':')[-1] # hardcoded papep_obj = arxiv.query(id_list=[paper_arxiv_id])[0] paper_link = papep_obj['pdf_url'].replace('http://', 'https://') + '.pdf' paper_link_name = paper_link.split("/pdf/")[1] print(paper_link) print(paper_link_name) req_pdf_size = requests.head(paper_link) pdf_size = round(int(req_pdf_size.headers["Content-Length"]) / 1024 / 1024, 2) query_answer = '{}. <a href="{}">{}</a>. {}\n\n— <a href="{}">{}</a>, {} Мб\n'.format( papep_obj['author_detail']['name'], papep_obj['arxiv_url'], escape(papep_obj['title'].replace('\n', ' ')), escape(papep_obj['summary'].replace('\n', ' ')), paper_link, paper_link_name, pdf_size ) await message.reply(query_answer, parse_mode="HTML", disable_web_page_preview=False) user_action_log(message, "arxiv random query was successful: " "got paper {}".format(papep_obj['arxiv_url'])) # TODO(randl): doesn't send. Download and delete? # my_bot.send_document(message.chat.id, data=paper_link) elif response.status_code == 503: # слишком часто запрашиваем action_log("Too much queries. 10 minutes break should be enough") arxiv_checker.last_call = datetime.datetime.utcnow() - datetime.timedelta(seconds=610) else: # если всё плохо user_action_log(message, "arxiv random query failed: response {}".format(response.status_code)) except Exception as ex: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] action_log("Unknown Exception: {}: {}\nat {} line {}".format(exc_type, ex, fname, exc_tb.tb_lineno))
def my_weather(message): """ Получает погоду в Москве на сегодня и на три ближайших дня, пересылает пользователю :param message: :return: """ try: my_owm = pyowm.OWM(tokens.owm) # где мы хотим узнать погоду my_obs = my_owm.weather_at_place('Moscow') except pyowm.exceptions.unauthorized_error.UnauthorizedError: print("Your API subscription level does not allow to check weather") return w = my_obs.get_weather() # статус погоды сейчас status = w.get_detailed_status() # температура сейчас temp_now = w.get_temperature('celsius') # limit=4, т.к. первый результат — текущая погода my_forecast = my_owm.daily_forecast('Moscow,RU', limit=4) my_fc = my_forecast.get_forecast() # температуры на следующие три дня my_fc_temps = [] # статусы на следующие три дня my_fc_statuses = [] for wth in my_fc: my_fc_temps.append(str(wth.get_temperature('celsius')['day'])) my_fc_statuses.append(str(wth.get_status())) # если всё нормально, то выводим результаты else: forecast = "The current temperature in Moscow is {} C, " \ "and it is {}.\n\n" \ "Tomorrow it will be {} C, {}.\n" \ "In 2 days it will be {}, {}.\n" \ "In 3 days it will be {} C, {}.".format(temp_now['temp'], status, my_fc_temps[1], my_fc_statuses[1], my_fc_temps[2], my_fc_statuses[2], my_fc_temps[3], my_fc_statuses[3]) my_bot.reply_to(message, forecast) user_action_log(message, "got that weather forecast")
async def my_wiki(message): wiki_title = '' if len(message.text.split()) == 1: wikipedia.set_lang(random.choice(['en', 'ru'])) wiki_query = wikipedia.random(pages=1) else: wiki_query = ' '.join(message.text.split()[1:]) user_action_log( message, 'entered this query for /wiki:\n{0}'.format(wiki_query)) if all(ord(x) < 127 or not x.isalpha() for x in wiki_query): wikipedia.set_lang('en') # TODO: a bit dirty condition elif all( ord(x) < 127 or ( ord('Ё') <= ord(x) <= ord('ё')) or not x.isalpha() for x in wiki_query): wikipedia.set_lang('ru') else: wikipedia.set_lang(detect(wiki_query)) try: wiki_page = wikipedia.page(title=wiki_query) wiki_title = wiki_page.title wiki_url = wiki_page.url wiki_fact = wikipedia.summary(wiki_query, sentences=5) if '\n \n' in str(wiki_fact): wiki_fact = '{}...\n\n' \ '<i>В данной статье имеется математическая вёрстка.\n' \ 'Для удобства чтения перейди по ссылке:</i>'.format(str(wiki_fact).split('\n \n', 1)[0]) await message.reply('<b>{0}.</b>\n{1}\n{2}'.format( wiki_title, wiki_fact, wiki_url), parse_mode='HTML') except wikipedia.exceptions.DisambiguationError as e: wiki_list = '\n'.join(map(str, e.options)) wiki_fact = '' await message.reply('Пожалуйста, уточни запрос.\n' \ 'Выбери, что из перечисленного имелось в виду, и вызови /wiki ещё раз.\n{0}'.format(wiki_list)) except wikipedia.exceptions.PageError: await message.reply('Запрос не найден.') user_action_log(message, "got Wikipedia article\n{0}".format(wiki_title))
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 flood_counter(message): # добавления счетчика в функцию if not hasattr(flood_counter, "disa_counter"): flood_counter.disa_counter = 0 if not hasattr(flood_counter, "time"): flood_counter.time = datetime.datetime.now() if not hasattr(flood_counter, "disa_id"): flood_counter.disa_id = 0 message_time = datetime.datetime.fromtimestamp(message.date) timediff = (message_time - flood_counter.time).seconds flood_counter.time = message_time if message.from_user.id != flood_counter.disa_id: flood_counter.disa_id = message.from_user.id flood_counter.disa_counter = 0 return if timediff > config.flood_time: user_action_log(message, "{} seconds from last message, dismissing".format(timediff)) flood_counter.disa_counter = 1 return flood_counter.disa_counter += 1
def admin_post(message): if len(message.text.split()) > 1: global_lock.acquire() if message.text.split()[1] == "edit": try: with open(config.file_location['last_post'], 'r', encoding='utf-8') as file: last_msg_id = int(file.read()) my_edited_message = ' '.join(message.text.split()[2:]) my_bot.edit_message_text(my_edited_message, config.mm_chat, last_msg_id, parse_mode="Markdown") user_action_log(message, "has edited message {}:\n{}".format(last_msg_id, my_edited_message)) except (IOError, OSError): my_bot.reply_to(message, "Мне нечего редактировать.") else: my_message = ' '.join(message.text.split()[1:]) sent_message = my_bot.send_message(config.mm_chat, my_message, parse_mode="Markdown") with open(config.file_location['last_post'], 'w', encoding='utf-8') as file_lastmsgID_write: file_lastmsgID_write.write(str(sent_message.message_id)) user_action_log(message, "has posted this message:\n{}".format(my_message)) global_lock.release() else: my_bot.reply_to(message, "Мне нечего постить.")
def admin_clean(message): if not hasattr(admin_clean, "allow_long"): admin_clean.allow_long = False if not hasattr(admin_clean, "allow_long_id"): admin_clean.allow_long_id = -1 if len(message.text.split()) == 1: if admin_clean.allow_long: user_action_log(message, "cancelled big cleanup") admin_clean.allow_long = False return else: num_str = message.text.split()[1] if not num_str.isdigit(): if admin_clean.allow_long: user_action_log(message, "cancelled big cleanup") admin_clean.allow_long = False return num = int(num_str) allow_long_str = 'Long cleanup is allowed' if admin_clean.allow_long else 'Long cleanup is not allowed' user_action_log(message, "has launched cleanup of {} messages. {}".format(num, allow_long_str)) if num > 500: my_bot.reply_to(message, "Тааак, падажжи, слишком большое число указал, больше 500 не принимаю") return if num > 128 and (not admin_clean.allow_long or admin_clean.allow_long_id != message.from_user.id): my_bot.reply_to(message, "Вы запросили очистку более 128 сообщений. Для подтверждения отправьте " "команду еще раз. Для отмены отправльте команду с текстовым параметром. " "С уважением, ваш раб") admin_clean.allow_long = True admin_clean.allow_long_id = message.from_user.id return count = 0 msg_id = message.message_id while count < num: try: my_bot.delete_message(chat_id=message.chat.id, message_id=msg_id) count += 1 except: pass msg_id -= 1 user_action_log(message, "cleaned up {} messages".format(count))
def disa(message): if not hasattr(disa, "disa_first"): disa.disa_first = True if not hasattr(disa, "disa_bang"): disa.disa_bang = time.time() if not hasattr(disa, "disa_crunch"): disa.disa_crunch = disa.disa_bang + 60 * 60 disa_init = False global_lock.acquire() # пытаемся открыть файл с количеством Дисиных хромосом try: with open(config.file_location_disa, 'r', encoding='utf-8') as file_disa_read: disa_chromo = int(file_disa_read.read()) except (IOError, OSError, ValueError): disa_chromo = 46 pass disa_chromo += 1 with open(config.file_location_disa, 'w', encoding='utf-8') as file_disa_write: file_disa_write.write(str(disa_chromo)) global_lock.release() user_action_log(message, "added chromosome to Disa") if message.chat.type == "supergroup": if disa.disa_first: disa.disa_bang = time.time() disa.disa_crunch = disa.disa_bang + 60 * 60 disa.disa_first = False elif (not disa.disa_first) and (time.time() >= disa.disa_crunch): disa_init = True # запись счетчика в вк if disa_init: disa_vk_report(disa_chromo, message)
def flood_counter(message): # добавления счетчика в функцию if not hasattr(flood_counter, "disa_counter"): flood_counter.disa_counter = 0 if not hasattr(flood_counter, "time"): flood_counter.time = datetime.datetime.now() if not hasattr(flood_counter, "disa_id"): flood_counter.disa_id = 0 message_time = datetime.datetime.fromtimestamp(message.date) timediff = (message_time - flood_counter.time).seconds flood_counter.time = message_time if message.from_user.id != flood_counter.disa_id: flood_counter.disa_id = message.from_user.id flood_counter.disa_counter = 0 return if timediff > config.flood_time: user_action_log( message, "{} seconds from last message, dismissing".format(timediff)) flood_counter.disa_counter = 1 return flood_counter.disa_counter += 1
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 arxiv_search(query, message): try: arxiv_search_res = arxiv.query(search_query=query, max_results=3) query_answer = '' for paper in arxiv_search_res: end = '…' if len(paper['summary']) > 251 else '' a_name = paper['authors'][0] if len(paper['authors'])>1: a_name += 'et al.' query_answer += \ '• {0}. <a href="{1}">{2}</a>. {3}{4}\n'.format( a_name, paper['arxiv_url'], escape(paper['title'].replace('\n', ' ')), escape(paper['summary'][0:250].replace('\n', ' ')), end) print(query_answer) user_action_log(message, "called arxiv search with query {}".format(query)) my_bot.reply_to(message, query_answer, parse_mode="HTML") except Exception as ex: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] action_log("Unknown Exception:\n{}: {}\nat {} line {}\n" "Creating the alert file.".format(exc_type, ex, fname, exc_tb.tb_lineno))
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 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 rules_command(message): if str(message.chat.id) == config.mm_chat: with open(config.file_location['/rules'], 'r', encoding='utf-8') as file: my_bot.reply_to(message, file.read(), parse_mode="HTML", disable_web_page_preview=True) user_action_log(message, "called rules")
def get_log(message): user_action_log(message, "requested bot logs") with open(config.file_location['bot_logs'], 'r', encoding='utf-8') as file: lines = file.readlines()[-100:] for text in cut_long_text(''.join(lines), max_len=3500): my_bot.reply_to(message, "{}".format(text))
def kek_enable(message): kek.my_kek.kek_enable = False user_action_log(message, "disabled kek")
def kek_enable(message): kek.my_kek.kek_enable = True user_action_log(message, "enabled kek")
def my_new_data(message): command = message.text.lower().split()[0] command_raw = re.split("@+", command)[0] with open(config.file_location[command_raw], 'r', encoding='utf-8') as file: my_bot.reply_to(message, file.read(), parse_mode="HTML", disable_web_page_preview=True) user_action_log(message, "called that command: {}".format(command))
def id_reply(message): my_bot.reply_to(message, message.text) user_action_log(message, "called echo:\n{}".format(message.text))
def id_reply(message): my_bot.reply_to(message, "/id") user_action_log(message, "called the id")
def underscope_reply(message): my_bot.reply_to(message, "_\\") user_action_log(message, "called the _\\")
def your_gender(message): with open(config.file_location['/gender'], 'r', encoding='utf-8') as file_gender: gender = random.choice(file_gender.readlines()) my_bot.reply_to(message, gender) user_action_log(message, "has discovered his gender:\n{0}".format(str(gender).replace("<br>", "\n")))
def my_roll(message): rolled_number = random.randint(0, 100) my_bot.reply_to(message, str(rolled_number).zfill(2)) user_action_log(message, "recieved {0}".format(rolled_number))
def my_truth(message): answers = ["да", "нет", "это не важно", "да, хотя зря", "никогда", "100%", "1 из 100"] truth = random.choice(answers) my_bot.reply_to(message, truth) user_action_log(message, "has discovered the Truth:\n{0}".format(truth))
def arxiv_random(message): user_action_log(message, "made arxiv random query") try: eastern = pytz.timezone('US/Eastern') eastern_time = datetime.datetime.now(eastern) # publications on 20:00 if eastern_time.hour < 20: eastern_time -= datetime.timedelta(days=1) # no publications on friday and saturday if eastern_time.weekday() == 5: eastern_time -= datetime.timedelta(days=2) elif eastern_time.weekday() == 4: eastern_time -= datetime.timedelta(days=1) last_published_date = eastern_time.strftime("%Y-%m-%d") response = requests.get('http://export.arxiv.org/oai2', params={'verb' : 'ListIdentifiers', 'set' : 'math', 'metadataPrefix': 'oai_dc', 'from' : last_published_date}) action_log("Random arxiv paper since {}".format(last_published_date)) # если всё хорошо if response.status_code == 200: response_tree = ElementTree.fromstring(response.content) num_of_papers = len(response_tree[2]) paper_index = random.randint(0, num_of_papers) paper_arxiv_id = response_tree[2][paper_index][0].text.split(':')[-1] # hardcoded papep_obj = arxiv.query(id_list=[paper_arxiv_id])[0] paper_link = papep_obj['pdf_url'].replace('http://', 'https://') + '.pdf' paper_link_name = paper_link.split("/pdf/")[1] print(paper_link) print(paper_link_name) req_pdf_size = requests.head(paper_link) pdf_size = round(int(req_pdf_size.headers["Content-Length"]) / 1024 / 1024, 2) a_name = papep_obj['authors'][0] if len(papep_obj['authors'])>1: a_name += 'et al.' query_answer = '{}. <a href="{}">{}</a>. {}\n\n— <a href="{}">{}</a>, {} Мб\n'.format( a_name, papep_obj['arxiv_url'], escape(papep_obj['title'].replace('\n', ' ')), escape(papep_obj['summary'].replace('\n', ' ')), paper_link, paper_link_name, pdf_size ) my_bot.reply_to(message, query_answer, parse_mode="HTML", disable_web_page_preview=False) user_action_log(message, "arxiv random query was successful: " "got paper {}".format(papep_obj['arxiv_url'])) # TODO(randl): doesn't send. Download and delete? # my_bot.send_document(message.chat.id, data=paper_link) elif response.status_code == 503: # слишком часто запрашиваем action_log("Too much queries. 10 minutes break should be enough") arxiv_checker.last_call = datetime.datetime.utcnow() - datetime.timedelta(seconds=610) else: # если всё плохо user_action_log(message, "arxiv random query failed: response {}".format(response.status_code)) except Exception as ex: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] action_log("Unknown Exception: {}: {}\nat {} line {}".format(exc_type, ex, fname, exc_tb.tb_lineno))
def my_wiki(message): """ Обрабатывает запрос и пересылает результат. Если запроса нет, выдаёт рандомный факт. :param message: :return: """ # обрабатываем всё, что пользователь ввёл после '/wiki ' if not len(message.text.split()) == 1: your_query = ' '.join(message.text.split()[1:]) user_action_log(message, "entered this query for /wiki:\n{0}".format(your_query)) try: # определяем язык запроса. Эвристика для английского и русского if all(ord(x) < 127 or not x.isalpha() for x in your_query): wikipedia.set_lang('en') # TODO: a bit dirty condition elif all(ord(x) < 127 or (ord('Ё') <= ord(x) <= ord('ё')) or not x.isalpha() for x in your_query): wikipedia.set_lang('ru') else: wikipedia.set_lang(detect(your_query)) wiki_response = wikipedia.summary(your_query, sentences=7) if '\n \n' in str(wiki_response): wiki_response = "{}...\n\n" \ "<i>В данной статье " \ "имеется математическая вёрстка. " \ "Ссылка на статью:</i>".format(str(wiki_response).split('\n \n', 1)[0]) # print(wiki_response) # извлекаем ссылку на саму статью wiki_url = parse.unquote(wikipedia.page(your_query).url) # извлекаем название статьи wiki_title = wikipedia.page(your_query).title my_bot.reply_to(message, "<b>{0}.</b>\n{1}\n\n{2}".format( wiki_title, wiki_response, wiki_url), parse_mode="HTML") user_action_log(message, "got Wikipedia article\n{0}".format(str(wiki_title))) # всё плохо, ничего не нашли except wikipedia.exceptions.PageError: my_bot.reply_to(message, "Запрос не найден.") user_action_log(message, "didn't received any data.") # нашли несколько статей, предлагаем пользователю список except wikipedia.exceptions.DisambiguationError as ex: wiki_options = ex.options my_bot.reply_to(message, "Пожалуйста, уточни запрос. " "Выбери, что из перечисленного имелось в виду, " "и вызови /wiki ещё раз.\n" + "\n".join(map(str, wiki_options))) print("There are multiple possible pages for that article.\n") # берём рандомную статью на рандомном языке (языки в config.py) else: wikipedia.set_lang(random.choice(['en', 'ru'])) wikp = wikipedia.random(pages=1) try: print("Trying to get Wikipedia article\n{0}".format(str(wikp))) wikpd = wikipedia.page(wikp) wiki_fact = wikipedia.summary(wikp, sentences=3) my_bot.reply_to(message, "<b>{0}.</b>\n{1}".format(wikpd.title, wiki_fact), parse_mode="HTML") user_action_log(message, "got Wikipedia article\n{0}".format(str(wikp))) except wikipedia.exceptions.DisambiguationError: wikp = wikipedia.random(pages=1) try: print("Trying to get Wikipedia article\n{0}".format(str(wikp))) wiki_var = wikipedia.search(wikp, results=1) print("There are multiple possible pages for that article.\n") # wikpd = wikipedia.page(str(wiki_var[0])) wiki_fact = wikipedia.summary(wiki_var, sentences=4) my_bot.reply_to(message, "<b>{0}.</b>\n{1}".format(wikp, wiki_fact), parse_mode="HTML") except wikipedia.exceptions.PageError: print("Page error for Wikipedia article\n{0}".format(str(wikp))) my_bot.reply_to(message, "<b>{0}.</b>".format("You're even unluckier"), parse_mode="HTML") except Exception as ex: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] action_log("Unknown Exception in Wikipedia: {}: {}\nat {} line {}".format(exc_type, ex, fname, exc_tb.tb_lineno)) except wikipedia.exceptions.PageError: print("Page error for Wikipedia article\n{0}".format(str(wikp))) my_bot.reply_to(message, "<b>{0}.</b>".format("You're very unlucky bastard"), parse_mode="HTML") except Exception as ex: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] action_log("Unknown Exception in Wikipedia: {}: {}\nat {} line {}".format(exc_type, ex, fname, exc_tb.tb_lineno))