def send_post(post: Post): query = db.session.query(Subscription).distinct(Subscription.chat_id) if post.city_id is not None: query = query.filter(Subscription.city_id == post.city_id) if post.position_id is not None: query = query.filter(Subscription.position_id == post.position_id) items = query.all() for subscription in items: if post.image_id: bot.send_photo( chat_id=subscription.chat_id, photo=post.image_id, caption=post.text, parse_mode="Markdown", disable_web_page_preview=False, ) else: bot.send_message( chat_id=subscription.chat_id, text=post.text, parse_mode='Markdown', disable_web_page_preview=False, ) post.date_sent = utc_now() db.session.commit() return items
def handle_callback_query(query): logger.info(query.data) # query.answer() chat_id = query.message.chat.id arr = query.data.split(":") query_type, query_value = arr[0], arr[1] if query_type == 'download_bilibili_cover': # 提取 B 站视频的封面图片 pic_url = services.get_bilibili_cover_img(query_value) bot.send_photo(chat_id=chat_id, photo=pic_url) elif query_type == 'download_bilibili_video': query.edit_message_text(text="小关正在加速为您下载视频,稍后会将下载链接呈上!!!") title = services.download_bilibili_video(query_value) logger.debug('Download {}'.format(title)) download_url = 'https://telegram.pushy.site/download/{}.flv'.format( title) bot.send_message(chat_id=chat_id, text='下载链接为: {}'.format(download_url)) elif query_type == 'download_zhihu_video': download_url = services.get_zhihu_video_download_url( 'https://www.zhihu.com/video/{}'.format(query_value)) query.edit_message_text(text=download_url)
def send_message_from_queue(): """Send message to users.""" try: queue = db_tools.get_users_for_message() except: return for queue_item in queue: message = json.loads(queue_item.message) if queue_item.marker: marker = json.loads(queue_item.marker) if marker and marker.get('action') == 'end': db_tools.set_end(queue_item.user) chat_id = queue_item.user.telegram_id reply_markup = make_keyboard(message.get('answers')) if message.get('img'): bot.send_photo( chat_id=chat_id, photo=message['img'], reply_markup=reply_markup, ) elif message.get('audio'): bot.send_voice( chat_id=chat_id, voice=message['audio'], reply_markup=reply_markup, ) elif message.get('document'): bot.send_document( chat_id=chat_id, data=message['document'], reply_markup=reply_markup, ) elif message.get('text'): if '{share_url}' in message['text']: message['text'] = message['text'].format(share_url=share_url + str(chat_id)) bot.send_message( chat_id=chat_id, text=message['text'], reply_markup=reply_markup, ) if queue_item.message_point: db_tools.set_story_point(queue_item.user, queue_item.message_point) if message.get('link'): db_tools.push_story_message_to_queue(queue_item.user, str(message.get('link'))) db_tools.delete_user_from_queue(queue_item)
def poster(bot, chatId, text=None, buttons=None, ed=False, message_id=None, doc=None, img=None, inline=False, lenRow=None): if buttons: if ed and not img and not doc: bot.edit_message_text(chat_id=chatId, message_id=message_id, text=text, reply_markup=keyboarder( buttons, inline, lenRow)) else: if img: bot.send_photo(chat_id=chatId, photo=img, reply_markup=keyboarder(buttons, inline, lenRow)) if text: bot.send_message(chatId, text, reply_markup=keyboarder( buttons, inline, lenRow)) if doc: bot.send_document(chat_id=chatId, data=doc, reply_markup=keyboarder( buttons, inline, lenRow)) else: if ed and not img and not doc: bot.edit_message_text(chat_id=chatId, message_id=message_id, text=text) else: if img: bot.send_photo(chat_id=chatId, photo=img) if text: bot.send_message(chatId, text) if doc: bot.send_document(chat_id=chatId, data=doc)
def send_messages(self, messages: list): """Отправляет набор сообщений Arguments: messages {list} -- Сообщения """ for message in messages: if "img" in message: photo = get_photo(message["img"]) bot.send_photo(self.chat_id, photo, caption=message["text"]) else: bot.send_message( self.chat_id, message["text"], parse_mode="Markdown", reply_markup=types.ReplyKeyboardRemove(), ) sleep(self.multimessages_delay)
def handle_page_size(message): try: shows_number = int(message.text) messages = http_requests.ParseData(http_requests.GetData(shows_number)) for one_message in messages: caption = "" if (type(one_message[2]) != str): continue if (type(one_message[1]) != str and type(one_message[0]) != str): continue if (type(one_message[0]) != str): caption = one_message[1] elif (type(one_message[1]) != str): caption = one_message[0] else: caption = one_message[0] + ' / ' + one_message[1] bot.send_photo(message.chat.id, one_message[2], caption=caption) time.sleep(1) except (TypeError, ValueError): bot.send_message(message.chat.id, 'A number, would you?')
def analyze_coin(cid, mid, coin_name): lang = db.get_lang(cid) curr = db.get_currency(cid) with get_coin_name(cid, coin_name) as coin: if coin is None: raise UnknownCoinError(coin_name) coin = coins[coin] xdate = [(date.today() - timedelta(days=x)).strftime('%d-%m-%Y') for x in range(10, 0, -1)] yprice = [ cg.get_coin_history_by_id( id=coin, date=d, string='false')['market_data']['current_price'][curr] for d in xdate ] bot.send_chat_action(cid, 'upload_photo') Path('./temp/image/').mkdir(parents=True, exist_ok=True) path = str(Path('./temp/image/' + str(cid) + str(mid) + '.png')) create_graph(xdate, yprice, path, coin, lang, curr) with open(path, 'rb') as plot: bot.send_photo(cid, plot) os.remove(path)
def ask_question(self, question: str, photo=None, location=False): """Выводит вопрос. Поведение отличается для вопросов в которых есть картинка или для вопросов которые подразумевают ответ геопозицией Arguments: question {str} -- Текст вопроса Keyword Arguments: photo {[type]} -- Картинка (default: {None}) location {[type]} -- Требуется ли ответ с геопозицией (default: {False:bool}) """ keyboard = None if location: keyboard = types.ReplyKeyboardMarkup() keyboard.add( types.KeyboardButton(text="Я на месте", request_location=True)) if photo: bot.send_photo(self.chat_id, photo, caption=question, reply_markup=keyboard) else: bot.send_message(self.chat_id, question, reply_markup=keyboard)
def command_start(update, context): from app import create_app app = create_app(config_class=Config) with app.app_context(): # удаляем сообщение chat_id = update.message.from_user.id message_id = update.message.message_id context.bot.delete_message(chat_id=chat_id, message_id=message_id) # функция обработки, если id пользователя в диплинке def handle_user_id(): user_id = deep_link.split('_')[1] sender: User = User.query.get(user_id) if sender: sender.tg_id = update.message.from_user.id db.session.commit() reply_markup = get_main_menu() with open('app/static/images/bot_images/Руки в стороны.jpeg', 'rb') as photo: context.bot.send_photo(chat_id=update.message.from_user.id, caption=texts.greeting(sender), photo=photo, reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN) context.bot.send_message( chat_id=chat_id, text='Кстати, вот ' '[короткая инструкция](https://telegra.ph/Instrukciya-po-rabote-v-chat-bote-Rosnano-11-27)', parse_mode=ParseMode.MARKDOWN) # если в составе команды пришел deep_link, то парсим и в отправляем в нужную функцию if len(update.message.text.split(' ')) > 1: deep_link = update.message.text.split(' ')[1] deep_link_dict = { 'userid': handle_user_id, } if deep_link.split('_')[0] in deep_link_dict: return deep_link_dict[deep_link.split('_')[0]]() # если в составе команды deep_link нет, то приветствуем пользователя else: user = User.query.filter_by( tg_id=update.message.from_user.id).first() if not user: user = User() user.tg_id = chat_id user.first_name = update.message.from_user.first_name db.session.add(user) db.session.commit() reg_btn = InlineKeyboardButton( text='Зарегистрироваться', url= f'{Config.VIDGET_PREFIX}/auth/registration?user_tg_id={update.message.from_user.id}' ) reply_markup = InlineKeyboardMarkup([[reg_btn]]) return bot.send_message(chat_id=update.message.from_user.id, text=texts.lets_register(), reply_markup=reply_markup) elif not user.phone or not user.email: user.set_subscribed() reg_btn = InlineKeyboardButton( text='Зарегистрироваться', url= f'{Config.VIDGET_PREFIX}/auth/registration?user_tg_id={update.message.from_user.id}' ) reply_markup = InlineKeyboardMarkup([[reg_btn]]) return bot.send_message(chat_id=update.message.from_user.id, text=texts.lets_register(), reply_markup=reply_markup) else: user.set_subscribed() with open('app/static/images/bot_images/Руки в стороны.jpeg', 'rb') as photo: bot.send_photo(chat_id=update.message.from_user.id, caption=texts.greeting(user), photo=photo, reply_markup=get_main_menu(), parse_mode=ParseMode.MARKDOWN) bot.send_message( chat_id=chat_id, text='Кстати, вот ' '[короткая инструкция](https://telegra.ph/Instrukciya-igry-Snezhnoe-loto-11-16)', parse_mode=ParseMode.MARKDOWN)
def handle_msg(msg): text = msg.text chat_id = msg.chat.id # 正则匹配 IP 地址 if utils.check_ip(text): # 查询 IP 地址 addr = services.query_ip(text) bot.send_message(chat_id=chat_id, text='该 IP 所处位置为: {}'.format(addr)) # 检测是否为包含 BV 号 elif text.startswith('BV') or text.startswith('bv') or text.startswith( 'https://b23.tv') or text.find('www.bilibili.com/video') != -1: bv = text if text.startswith('https://b23.tv'): bv = text[15:27] if text.find('www.bilibili.com/video') != -1: bv = re.findall('www.bilibili.com/video/(.*?)\?', text, re.S)[0] keyboard = [[ InlineKeyboardButton( "下载封面", callback_data='download_bilibili_cover:{}'.format(bv)), InlineKeyboardButton( "下载视频", callback_data='download_bilibili_video:{}'.format(bv)) ]] reply_markup = InlineKeyboardMarkup(keyboard) bot.send_message(chat_id=msg.chat.id, text='检测到 Bilibili 链接,您想让小关干嘛呢?', reply_markup=reply_markup) # 检测是否为淘口令、京东链接等 elif text.find('https://m.tb.cn/') != -1 or text.startswith( 'https://item.m.jd.com/product'): bot.send_message(chat_id=chat_id, text='{}正在为您查询该商品的价格哦,请稍等哈!'.format(config.BOT_NAME)) if text.find('https://m.tb.cn/') != -1: # 从淘口令中提取短连接 tb_id = re.findall('https://m\.tb\.cn/(.*?)\?sm=', text, re.S)[0] item_link = 'https://m.tb.cn/{}'.format(tb_id) elif text.startswith('https://item.m.jd.com/product'): item_link = text else: logger.error('无效的商品链接: {}'.format(text)) bot.send_message(chat_id=msg.chat.id, text='无效的商品链接') return img_path, suggestion = services.query_price(item_link) if not img_path and not suggestion: # 暂未收录该商品 bot.send_message(chat_id=msg.chat.id, text='该商品暂未被收录哦!') else: bot.send_photo(chat_id=msg.chat.id, photo=open(img_path, 'rb')) bot.send_message(chat_id=msg.chat.id, text=suggestion) # 检测是否为知乎视频的分享链接 elif text.find('https://www.zhihu.com/zvideo/') != -1: bot.send_message(chat_id=chat_id, text='{}正在为您搜寻,稍后会将下载链接呈上 😊😊😊'.format( config.BOT_NAME)) zvideo_id = re.findall('https://www.zhihu.com/zvideo/(.*?)\?', text, re.S)[0] video_src_url = services.get_zhihu_video_link(zvideo_id) logger.info('Find video ') bot.send_message(chat_id=chat_id, text=video_src_url) # 检测是否为知乎答案的分享链接 elif text.find('https://www.zhihu.com/question/') != -1: question_url = 'https://{}'.format( re.findall('https://(.*?)\?', text, re.S)[0]) download_list = services.get_download_list_by_question_url( question_url) keyboard = [] for each in download_list: keyboard.append( InlineKeyboardButton( text=each['title'], callback_data='download_zhihu_video:{}'.format( each['video_id']))) reply_markup = InlineKeyboardMarkup([keyboard]) bot.send_message(chat_id=msg.chat.id, text='请选择你要下载的视频:', reply_markup=reply_markup) # 处理类似 /help 命令的文本 elif text.startswith('/'): command = text[1:] bot.send_message(chat_id=chat_id, text=handle_command(command)) elif text.find('你好') != -1: bot.send_message(chat_id=chat_id, text='你好啊,我的名字叫{},很高兴认识你!'.format(config.BOT_NAME)) else: bot.send_message(chat_id=chat_id, text=text)