def random_joke(message): ''' Sending random joke from rzhunemogu.ru in chat ''' resp = requests.get("http://rzhunemogu.ru/RandJSON.aspx?CType=1") if resp.status_code == 200: utf8content = resp.content.decode("windows-1251").encode( 'utf-8').decode('utf-8') json_joke = json.loads(utf8content.replace('\r\n', '\\r\\n')) message.text = "{}\nАХ-ХАХАХАХХАХА! лолол!".format(json_joke) if len(json_joke['content']) > 200: file = text_to_speech(json_joke['content']) with open(file, 'rb') as audio: voice_msg = bot.send_voice( message.chat.id, reply_to_message_id=message.message_id, voice=audio, caption=json_joke['content'][:200]) bot.send_message(message.chat.id, reply_to_message_id=voice_msg.message_id, text=json_joke['content'][200:]) else: file = text_to_speech(json_joke['content']) with open(file, 'rb') as audio: bot.send_voice(message.chat.id, voice=audio, caption=json_joke['content'], reply_to_message_id=message.message_id)
def random_message(message, string_list, mode): ''' Sands random massage and sticker Parameters ---------- message : str message from chat string_list : str Json list with texts mode : type SEND_MESSAGE, REPLY_MESSAGE ''' strings_num = len(string_list['strings']) r_number = randrange(0, strings_num, 1) if string_list['strings'] and string_list['strings'][r_number]: if mode is SEND_MESSAGE: bot.send_message(message.chat.id, string_list['strings'][r_number], parse_mode='Markdown') elif mode is REPLY_MESSAGE: bot.reply_to(message, string_list['strings'][r_number], parse_mode='Markdown') if string_list['stickers'] and string_list['stickers'][r_number]: bot.send_sticker(message.chat.id, string_list['stickers'][r_number])
def on_user_joins(message): logger.info("New chat member, username: @{:s}".format( message.from_user.username or "NONE")) print(message) if re.search(r"\b[bб6][оo][т7t]\b", message.from_user.first_name, re.IGNORECASE | re.UNICODE) or \ re.search(r"\b[bб6][оo][т7t]\b", message.from_user.last_name, re.IGNORECASE | re.UNICODE): if message.from_user.username is not None: username_str = '@{}'.format(message.from_user.username) else: username_str = message.from_user.first_name or 'Ноунейм' message_str = "Возможно [{}] - это бот!\n@via_tcp\n@content_of_brain\n@lopotyana".format( username_str) bot.send_message(message.chat.id, message_str) bot.restrict_chat_member(message.chat.id, message.from_user.id, 0, False, False, False, False) return # Use firstname if username is NONE if message.from_user.username is not None: username_str = '@{}'.format(message.from_user.username) else: username_str = message.from_user.first_name or 'Ноунейм' message_str = "{} готов(а) сжигать пукан свой в пепел вместе с нами!!🔥\nВстречайте героя!👻".format( username_str) bot.send_message(message.chat.id, message_str)
def dota_news(message): if intime(message): cid = getCID(message) content = getContent(message) url = "http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=570&count=1&maxlength=300&format=json" request = requests.get(url) data = request.json() if content != "?": if request.status_code == 200: title = data['appnews']['newsitems'][0]['title'] content = data['appnews']['newsitems'][0]['contents'] content_nice = content.replace(" - ", "\n - ") content_nice = content_nice.replace("*", "\n*") content_nice = parser.unescape(content_nice) url = data['appnews']['newsitems'][0]['url'] bot.send_message( cid, u'*{title}*```> \n{content_nice}\n[...]\n```'.format(title=title, content_nice=content_nice) + u'[More info here]({url})'.format(url=url), parse_mode="Markdown", disable_web_page_preview=True) else: bot.reply_to( message, "`There has been an error, the number {error} to be specific.`" .format(error=request.status_code), parse_mode="Markdown") else: bot.reply_to( message, "`Send this command alone and I will show you the last Steam News for Dota2 entry`", parse_mode="Markdown")
async def notify_at(hours, minuites): while True: await match_time((hours, minuites)) today = datetime.date(datetime.now()) Session = sessionmaker(bind=engine) session = Session() raw_tasks = session.query(Task).filter(Task.date==today).all() state = dp.current_state(user=MY_ID) for id_ in {MY_ID}: if len(raw_tasks) == 0: bot.send_message(id_, "Нет задач на сегодня") else: keyboard = types.InlineKeyboardMarkup() for index, t_ in enumerate(raw_tasks): button = types.InlineKeyboardButton(f"({t_.id_}). {str(t_.date)}, {t_.task}", callback_data = t_.id_) keyboard.add(button) await bot.send_message(id_,"Доброго времени суток!\nНажмите на текст задачи, чтобы ее изменить", reply_markup=keyboard) await bot.send_voice(id_, VOICE) await state.set_state( ManageTasks.waiting_for_task_choice) await match_time((0, 0))
def start_command(message): logger.info("/start command by {:s}, Username {:s}".format( message.from_user.first_name, (message.from_user.username or "NONE"))) if message.chat.id > 0: bot.send_message( message.chat.id, ru_strings.START_MESSAGE['strings'][0].format( message.chat.first_name)) sleep(2) info_command(message)
def photo_receive(message): ''' Recognizes photos with the comment "персик" Ban for NSFW ''' file_id = message.photo[len(message.photo) - 1].file_id if message.caption and message.forward_from is None: if re.match('(?i)(\W|^).*?!п[eеэ][pр][cс](и|ч[eеи]к).*?(\W|$)', message.caption): bot.reply_to(message, "".join([ message.from_user.first_name, picturedetect.reply_get_concept_msg(file_id) ]), parse_mode='Markdown') logger.info("Photo by Username @{:s} | ID {:s}".format( (message.from_user.username or "NONE"), file_id)) try: os.makedirs("./photos") except FileExistsError: pass file_patch = './photos/{:s}.jpg'.format(file_id) _file = Path(file_patch) if _file.is_file() is not True: file_info = bot.get_file(file_id) file_patch = utils.file_download(file_info, './photos/') if file_patch is None: logger.error("File download error!'") bot.reply_to(message, ru_strings.SOME_ERROR_MESSAGE['strings'], parse_mode='Markdown') bot.send_sticker(message.chat.id, ru_strings.SOME_ERROR_MESSAGE['stickers'][0]) return if not allow_nsfw: if picturedetect.nsfw_test(file_patch, 0.75): bot.delete_message(message.chat.id, message.message_id) bot.send_message( message.chat.id, "*{} уходит в бан на {} {}! Причина: NSFW*".format( message.from_user.first_name, 2, 'мин.'), parse_mode='Markdown') ban_user(message.chat.id, message.from_user.id, 2 * 60)
def send_to_admin(message, text, admins, is_forward): text = text.format(get_user(message.reply_to_message.forward_from)) if is_forward else \ text.format(get_user(message.reply_to_message.from_user)) try: bot.send_message(message.from_user.id, text) logger.info(text.format(get_user(message.reply_to_message.from_user))) except ApiException as e: if str(e.result) == r'<Response [403]>': reply_msg = text + '\nI can\'t contact you. Please start a chat with me.' bot.reply_to(message, reply_msg) logger.error('Admin {} couldn\'t be reached'.format( admins[message.from_user.id]))
def restart(message): if message.chat.type != 'private': return current_controller.start_session(message) keyboard = types.InlineKeyboardMarkup() keyboard.row(types.InlineKeyboardButton(text="МГУ", callback_data="set_school_msu"), types.InlineKeyboardButton(text="ВШЭ", callback_data="set_school_hse")) keyboard.add(types.InlineKeyboardButton(text="Другой", callback_data="set_school_other")) bot.send_message(message.from_user.id, "❓ Укажите свой вуз", parse_mode="HTML", reply_markup=keyboard) build_child(message)
def false_ban(message): ''' Ban prank KEK For meanmail exclusive ''' orig_time = time = 40 if message.chat.type != 'private' and message.reply_to_message is None: bot.delete_message(message.chat.id, message.message_id) time_str = re.search('[0-9]{1,8}', message.text) if time_str: orig_time = time = int(time_str.group(0)) time_time = re.search('([0-9]{1,5})\s?(с(ек)?|м(ин)?|ч(ас)?|д(ен|н)?)', message.text) time_text = 'сек.' if time_time: text = re.search('[А-Яа-я]{1,2}', time_time.group(0)) if text: if text.group(0)[0] == "м": time = time * 60 time_text = "мин." elif text.group(0)[0] == "ч": time = time * 60 * 60 time_text = "ч." elif text.group(0)[0] == "д": time = time * 24 * 60 * 60 time_text = "д." user_to_ban = None ban_message_num = int(time < 30) if message.chat.type == 'private': user_to_ban = message.reply_to_message.forward_from elif message.reply_to_message is None: user_to_ban = message.from_user ban_message_num = 2 else: user_to_ban = message.reply_to_message.from_user if message.from_user.id == message.reply_to_message.from_user.id: ban_message_num = 2 try: bot.send_message( config.send_chat_id, ru_strings.BAN_MESSAGE['strings'][ban_message_num].format( user_to_ban.first_name, orig_time, time_text), parse_mode='Markdown') except Exception as e: logger.error("[ban_command()] Unexpected error: {}".format(e))
def user_penalty_off(message): ''' Disables the restriction of users to use certain letters. ''' bot.delete_message(message.chat.id, message.message_id) if message.reply_to_message: if penalty_users_id.count(message.reply_to_message.from_user.id) == 1: penalty_users_id.remove(message.reply_to_message.from_user.id) bot.send_message( message.chat.id, "*Пользователь {} прощен!*".format( message.reply_to_message.from_user.first_name), parse_mode='Markdown')
def user_penalty_on(message): ''' Enables the restriction of users to use certain letters. ''' bot.delete_message(message.chat.id, message.message_id) if message.reply_to_message: if penalty_users_id.count(message.reply_to_message.from_user.id) == 0: penalty_users_id.append(message.reply_to_message.from_user.id) bot.send_message( message.chat.id, "*Пользователь {} наказан! Недоступны буквы: a, у, е*".format( message.reply_to_message.from_user.first_name), parse_mode='Markdown')
def angry_ban(message): ''' Ban with angry stickers ''' bot.send_sticker(message.chat.id, 'CAADAgADJwMAApFfCAABfVrdPYRn8x4C') if message.chat.type != 'private': sleep(4) ban_user(config.send_chat_id, message.from_user.id, 120) bot.send_message(message.chat.id, ru_strings.BAN_MESSAGE['strings'][0].format( message.from_user.first_name, 2, 'мин.'), parse_mode='Markdown') bot.send_sticker(message.chat.id, 'CAADAgADPQMAApFfCAABt8Meib23A_QC')
def dota_blog(message): if intime(message): cid = getCID(message) dota_blog_rss_url = "http://blog.dota2.com/feed/" feed = feedparser.parse(dota_blog_rss_url) post_title = feed["items"][0]["title"] post_link = addBlogPostInstantView(feed["items"][0]["link"]) bot.send_message( cid, u'*{title}* ```\n\n```' .format(title = post_title) + u'[Read the latest blog post in your browser]({url})' .format(url = post_link), parse_mode = "Markdown")
def send_message(message): if message.text: if message.text.find('/cancel') != -1: bot.send_message(message.chat.id, ru_strings.CANCEL_MESSAGE['strings'][0], parse_mode='Markdown') else: bot.send_message(config.send_chat_id, message.text, parse_mode='Markdown') logger.info("Sending message {:s} to chat {:d}".format( message.text, config.send_chat_id)) bot.send_message(message.chat.id, ru_strings.SEND_MSG_MESSAGE['strings'][1], parse_mode='Markdown') elif message.photo: try: os.makedirs("./photos") except FileExistsError: pass file_id = message.photo[len(message.photo) - 1].file_id file_info = bot.get_file(file_id) file_patch = utils.file_download(file_info, './photos/') with open(file_patch, 'rb') as photo: bot.send_photo(config.send_chat_id, photo) logger.info("Sending photo {:s} to chat {:d}".format( file_id, config.send_chat_id)) bot.send_message(message.chat.id, ru_strings.SEND_MSG_MESSAGE['strings'][1], parse_mode='Markdown')
def chair_bonjour(call): new_user_id = call.data[len( 'choice1$'):] # substring ID from callback data if new_user_id != str(call.from_user.id): # Ignore existing chat memders return # Delete our message bot.delete_message(call.message.chat.id, call.message.message_id) if 'choice1' in call.data: # First button or second button(choice1 or choice2) logger.info("[Bonjour]: @{:s} pressed FIRST button!".format( call.from_user.username or "NONE")) # Getting current timestamp d = datetime.utcnow() d = d + timedelta(0, 30) timestamp = calendar.timegm(d.utctimetuple()) # Catch "user is an administrator of the chat" Exception try: # Ban user from chat for 30 seconds bot.kick_chat_member(call.message.chat.id, new_user_id, until_date=timestamp) except Exception: logger.info( "[EXCEPTION] Bad Request: User is an administrator of the chat!" ) else: logger.info("[Bonjour]: @{:s} pressed SECOND button!".format( call.from_user.username or "NONE")) # Use firstname if username is NONE if call.from_user.username is not None: username_str = '@{}'.format(call.from_user.username) else: username_str = call.from_user.first_name or 'Ноунейм' bot.send_message( call.message.chat.id, username_str + ' решил(а) остатся!☝️ \nВстречайте героя!👻') # Catch "can't demote chat creator" Exception try: # Unrestrict user bot.restrict_chat_member(call.message.chat.id, call.from_user.id, 1, True, True, True, True) except Exception: logger.info("[EXCEPTION] Bad Request: can't demote chat creator!")
def notify_users_and_groups(message): # Notify subscribed users for user_id in loadjson("userlist"): try: bot.send_message(user_id, message, parse_mode="Markdown") except telebot.apihelper.ApiException as ex: USER_BLOCK_ERROR = "Forbidden: bot was blocked by the user" if (USER_BLOCK_ERROR in str(ex)): print( "{date}: The user {user_id} has blocked the bot. The user will be removed." .format(date=datetime.now(), user_id=user_id), file=log) deljson(user_id, "userlist") else: telebot.logger.error(ex) print( "{}: Message could not be sent to group - Telebot API Error" .format(datetime.now()), file=log) except Exception as ex: telebot.logger.error(ex) print("{}: Message could not be sent to users".format( datetime.now()), file=log) # Notify subscribed groups for gid in loadjson("grouplist").keys(): try: bot.send_message(gid, message, parse_mode="Markdown") except telebot.apihelper.ApiException as ex: GROUP_BLOCK_ERROR = "Forbidden: bot was kicked from the group chat" if (GROUP_BLOCK_ERROR in str(ex)): print( "{date}: The group {gid} has kicked the bot. The group will be removed." .format(date=datetime.now(), gid=gid), file=log) deljson(gid, "grouplist") else: telebot.logger.error(ex) print( "{}: Message could not be sent to group - Telebot API Error" .format(datetime.now()), file=log) except Exception as ex: telebot.logger.error(ex) print("{}: Message could not be sent to groups".format( datetime.now()), file=log)
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 stk_command(message): logger.info("/stk command by {:s}, Username @{:s}".format( message.from_user.first_name, (message.from_user.username or "NONE"))) if message.chat.type != "private": return administrators = bot.get_chat_administrators(config.send_chat_id) if any(message.from_user.id == member.user.id for member in administrators): logger.info("The owner detected!") bot.send_message(message.chat.id, ru_strings.SEND_STICKER_MESSAGE['strings'][0], parse_mode='Markdown') bot.register_next_step_handler(message, send_sticker) else: logger.info("This isn't the owner!")
def byban(message): ''' Restriction for all versions of word Беларуссия ''' bot.send_sticker(message.chat.id, 'CAADAgADGwAD0JwyGF7MX7q4n6d_Ag', reply_to_message_id=message.message_id) if message.chat.type == 'private': return else: bot.send_message(message.chat.id, "*{} ушел искать белоруссию на 5 минут!*".format( message.from_user.first_name), parse_mode='Markdown') ban_user(message.chat.id, message.from_user.id, 60 * 5)
def notify_users_and_groups(message): # Notify subscribed users for user_id in loadjson("userlist"): try: bot.send_message(user_id, message, parse_mode="Markdown") except: print("{}: Message could not be sent to users".format( datetime.now()), file=log) # Notify subscribed groups for gid in loadjson("grouplist").keys(): try: bot.send_message(gid, message, parse_mode="Markdown") except: print("{}: Message could not be sent to groups".format( datetime.now()), file=log)
def report_to_admins(message): """Sends a link to a user's reported message with a reporter's reason to the admins """ from_chat = config.chat_name[1:] reported_id = message.reply_to_message.message_id reason = message.text.split(maxsplit=1) reported_msg = "https://t.me/{0}/{1}\n{2}".format( from_chat, reported_id, reason[1][:30] if len(reason) > 1 else "") for admin_id in config.admin_ids: try: bot.send_message(admin_id, reported_msg) except ApiException as e: if str(e.result) == config.unreachable_exc: continue logger.info("Message {} has been successfully reported".format( message.reply_to_message.message_id))
def rate_command(message): if "@" in message.text: if "alphaofftopbot" not in message.text: return msg_to_update = bot.send_message(message.chat.id, "*loading..*", parse_mode='Markdown') update_crypto_rate(msg_to_update)
def send_sticker(message): if message.content_type != 'sticker': if message.text is not None: if message.text.find('/cancel') != -1: bot.send_message(message.chat.id, ru_strings.CANCEL_MESSAGE['strings'][0], parse_mode='Markdown') else: bot.send_message( message.chat.id, ru_strings.SEND_STICKER_MESSAGE['stickers'][1], parse_mode='Markdown') bot.register_next_step_handler(message, send_sticker) else: bot.send_sticker(config.send_chat_id, message.sticker.file_id) logger.info("Sending sticker {:s} to chat {:d}".format( message.sticker.file_id, config.send_chat_id))
def roulette_game(message): if message.chat.type != 'private': # Only in chat r_number = randrange(0, 6) if r_number == 3: bot.send_message(message.chat.id, ru_strings.ROULETTE_MESSAGE['strings'][0].format( message.from_user.first_name), parse_mode='Markdown') ban_user(config.send_chat_id, message.from_user.id, 1200) else: msg = bot.send_message( message.chat.id, ru_strings.ROULETTE_MESSAGE['strings'][1].format( message.from_user.first_name), parse_mode='Markdown') sleep(10) bot.delete_message(message.chat.id, message.message_id) bot.delete_message(msg.chat.id, msg.message_id)
def togglensfw(message): global allow_nsfw administrators = bot.get_chat_administrators(config.send_chat_id) if any(message.from_user.id == member.user.id for member in administrators): allow_nsfw = not allow_nsfw if allow_nsfw is True: bot.send_message(message.chat.id, ru_strings.NSFW_TOGGLE_MESSAGE['strings'][1], parse_mode='Markdown') else: bot.send_message(message.chat.id, ru_strings.NSFW_TOGGLE_MESSAGE['strings'][0], parse_mode='Markdown') logger.info("/togglensfw command by {:s}, Username @{:s}".format( message.from_user.first_name, (message.from_user.username or "NONE")))
def exch_command(message): resp = requests.get("http://cbr.ru/scripts/XML_daily.asp", stream=True) if resp.status_code == 200: root = etree.fromstring( resp.content.decode("windows-1251").encode('utf-8').decode( 'utf-8')) exch = '' for valute in root.findall('Valute'): if valute.get('ID') == 'R01235': exch = valute.find('Value').text break bot.send_message(message.chat.id, "1 USD = {} RUB".format(exch), parse_mode='Markdown') resp = requests.get("http://www.nbrb.by/API/ExRates/Rates/USD?ParamMode=2") if resp.status_code == 200: json_obj = json.loads(resp.content.decode("utf-8")) bot.send_message(message.chat.id, "1 USD = {} BYN".format(json_obj['Cur_OfficialRate']), parse_mode='Markdown') resp = requests.get( "https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json") if resp.status_code == 200: json_obj = json.loads(resp.content.decode("utf-8")) exch = '' for curr in json_obj: if curr['cc'] == 'USD': exch = curr['rate'] break bot.send_message(message.chat.id, "1 USD = {} UAH".format(exch), parse_mode='Markdown')
def my_report(message): """Handles users' reports """ if not r.get(message.reply_to_message.message_id): report_to_admins(message) r.set(message.reply_to_message.message_id, 1, ex=60 * config.ro_span_mins) response = bot.send_message( chat_id=message.chat.id, text="Мы примем все необходимые меры, спасибо.") Timer( 30, bot.delete_message, kwargs={ "chat_id": response.chat.id, "message_id": response.message_id }, ).start() elif r.incr( message.reply_to_message.message_id) >= config.report_threshold: ro_giver(message, r)
def birthday_method(): ''' Automatically publishes greetings from the list Still in test mode! TODO: replace chat_id ''' logger.info('Birthday thread started!') chat_id = '-1001464920421' # Test chat id while True: todaytime = datetime.today() if bot.get_chat(chat_id).pinned_message is not None: pinnedmessage = bot.get_chat(chat_id).pinned_message.text else: pinnedmessage = 'none' for birthday in birthdays.BIRTHDAYS_LIST: birthdatetime = birthday[birthdays.date] delta = birthdatetime - todaytime # print(delta.total_seconds()) if (delta.total_seconds() < 0 and delta.total_seconds() > -86400): # 86400 secs = 24 hours pinmessage = birthday[birthdays.message] if (pinmessage != pinnedmessage): # bot.send_message(message.chat.id, "ЗАМЕНИТЬ ВСЕ НАХРЕН") #DEBUG msg_topin = bot.send_message(chat_id, birthday[birthdays.message]) sleep(1) # Antispam bot.pin_chat_message(chat_id, msg_topin.message_id) # bot.send_message(message.chat.id, "ВСЕ ВЕРНО") #DEBUG sleep(30 * 60)
def end_subscription(message): uid = str(message.from_user.id) cid = str(message.chat.id) if message.chat.type == 'private': if uid in loadjson("userlist"): deljson(uid, "userlist") bot.send_message(uid, 'You have been removed from the subscription list', parse_mode="Markdown") else: bot.send_message(uid, 'You can\'t unsubscribe without subscribing first dummy!', parse_mode="Markdown") elif message.chat.type == 'group' or message.chat.type == 'supergroup': if cid in loadjson("grouplist"): bot.reply_to(message, 'Oh, no more updates? Okay...', parse_mode="Markdown") gid = str(message.chat.id) deljson(gid, "grouplist") else: bot.send_message(cid, 'Not subscibed yet', parse_mode="Markdown") else: pass
def start_subscription(message): uid = str(message.from_user.id) cid = str(message.chat.id) if message.chat.type == 'private': if uid not in loadjson("userlist"): addUser(uid, message.from_user.first_name, "userlist") bot.send_message(uid, 'You will now receive updates!', parse_mode="Markdown") else: bot.send_message(uid, 'halloooooo', parse_mode="Markdown") elif message.chat.type == 'group' or message.chat.type == 'supergroup': if cid not in loadjson("grouplist"): bot.reply_to( message, 'Hello fans, this awesome group is now added and I will keep you guys up to date', parse_mode="Markdown") gid = str(message.chat.id) gname = message.chat.title addUser(gid, gname, "grouplist") else: bot.send_message(cid, 'Hello again fans, your group has already been registered', parse_mode="Markdown") else: pass
def find_match(message): if intime(message): cid = getCID(message) content = getContent(message) match_id = message.text match_id = match_id.split()[1] try: match = api.get_match_details(match_id) url = match.url request = requests.get(url) match_data = request.json() if content != "?": if request.status_code == 200: hero_list = [] if match_data['result']['radiant_win']: title = "Radiant!" else: title = "Dire!" url = "http://www.dotabuff.com/matches/" + match_id radiant_content = "" dire_content = "" for player in match_data['result']['players']: if player['player_slot'] < 100: # radiant for hero in heroes_list: if hero['id'] == player['hero_id']: hero_list.append(hero['localized_name']) radiant_content = (radiant_content + hero['localized_name'] + " " + str(player['kills']) + "/" + str(player['deaths']) + "/" + str(player['assists']) + '\n') else: # dire for hero in heroes_list: if hero['id'] == player['hero_id']: hero_list.append(hero['localized_name']) dire_content = (dire_content + hero['localized_name'] + " " + str(player['kills']) + "/" + str(player['deaths']) + "/" + str(player['assists']) + '\n') bot.send_message( cid, 'Winner: *{title}* \n _Radiant:_ \n{radiant}\n _Dire:_\n{dire}\n' .format(title=title, radiant=radiant_content, dire=dire_content) + '[Dotabuff link]({url})'.format(url=url), parse_mode="Markdown", disable_web_page_preview=True) else: bot.reply_to( message, "`There has been an error, the number {error} to be specific.`".format(error=request.status_code), parse_mode="Markdown") else: bot.reply_to(message, "`wat`", parse_mode="Markdown") except Exception as ex: bot.reply_to( message, "There has been an error, its message is:\n `{error}`".format(error=ex.msg), parse_mode="Markdown")