def catch(self): p = 0 try: cam = cv2.VideoCapture(0, cv2.CAP_DSHOW) # вкл. камеры except: cam = cv2.VideoCapture(1, cv2.CAP_DSHOW) while p < 2: # количество снимков p += 1 ret, frame = cam.read() # делаем снимок cv2.imwrite('cam.png', frame) # сохраняем снимок камеры sct.shot(output='scr.png') photo = open('cam.png', 'rb') # откр. для чтения в двоичном режиме screen = open('scr.png', 'rb') # сохраняем скриншот экрана media = [InputMediaPhoto(photo), InputMediaPhoto(screen)] try: bot.send_media_group(chat_id, media) # отправка в телеграм except: pass time.sleep(random.uniform(1, 3)) # задержка от 1 до 3 сек. cam.release() # откл. камеру time.sleep(5) self.m_position = mouse.position # переназначим позицию мышки return self.main()
def cmd_tovari(message): # bot.send_message(message.chat.id, 'Товары: ') tovars = session.query(Tovar).all() text = "Товары:\n" for tovar in tovars: asd = f"{tovar.name}: {tovar.amount}шт. цена: {tovar.cost}р./шт.\n" text += asd bot.send_message(message.chat.id, text) # https://ibb.co/GRLF6q7 # https://ibb.co/8rqyvMs # https://ibb.co/VqbRr5J IMG_URLS = [ 'AgACAgIAAxkDAAIBdl-PWLDMNhdz4mlac5lOqJEOvQ5MAAJirzEbx_h4SNXZelGYQeQ0m6zrly4AAwEAAwIAA3gAA14JAgABGwQ', 'AgACAgIAAxkDAAIBeF-PWLDl67c6iViG_hxhMxDr41X6AAJjrzEbx_h4SFmns-q3adzdqSfNly4AAwEAAwIAA3kAAyrcAQABGwQ', 'AgACAgIAAxkDAAIBel-PWLBCzoLjFCfAz-r0LHrppwHUAAJkrzEbx_h4SCyWq44R01HEyWNQmC4AAwEAAwIAA3gAA_b1AQABGwQ' ] bot.send_media_group(message.chat.id, [ InputMediaPhoto(IMG_URLS[0]), InputMediaPhoto(IMG_URLS[1]), InputMediaPhoto(IMG_URLS[2]), ]) dbworker.set_state(message.chat.id, config.States.S_DEFAULT.value)
def print_posts(post, bot, choose, query, true_choose): for pop in post: image = pop.images.all() image = PostImage.objects.filter(post=pop) img_list = [] listToStr = ',\n '.join([str(elem) for elem in pop.link_list]) for i in image: img_list.append(str(i.images)) media_group = list() for number, url in enumerate(img_list): if number == 1: media_group.append(InputMediaPhoto(media=url)) else: media_group.append(InputMediaPhoto(media=url)) bot.send_media_group(query.message.chat_id, media=media_group) bot.send_message( chat_id=query.message.chat_id, text= f"Название : {pop.title}\nОписание : {pop.description}\nКонтакты: {pop.phone} \nМы в соц.сетях : {listToStr}" ) btn_more = [[ InlineKeyboardButton('More', callback_data=f'{true_choose}'), ]] keyboard_more = InlineKeyboardMarkup(btn_more, resize_keyboard=False) bot.send_message(chat_id=query.message.chat_id, text="Чтобы посмотреть больше нажмите кнопку ниже", reply_markup=keyboard_more)
def all_messages_handler(message: Message): if message.content_type == 'location' and message.location is not None: chat_id = message.chat.id bot.send_chat_action(chat_id, action='Typing') location = message.location # location = Location(latitude=55.790996, longitude=37.5839) object_info = load_object_info(location) if object_info is not None: logger.debug('Object has been found') photo_url = object_info.photo_url text = make_object_text(object_info) precise_location = object_info.location photos = [] if photo_url is not None: photo = load_photo(photo_url) if photo is not None: photos.append(photo) photos += load_retro_photos(location) if len(photos) == 1: logger.debug('Sending single photo') bot.send_photo( chat_id, photos[0], caption=text, ) else: # Send multiple files if len(photos) > 1: media_items = [InputMediaPhoto(photos.pop(0), caption=text, parse_mode='Markdown')] media_items += map(lambda file: InputMediaPhoto(file), photos) logger.debug('Sending media group') bot.send_media_group(chat_id, media_items) else: logger.debug('Sending text without photos') bot.send_message(chat_id, text=text) # Send map with precise object location if precise_location is not None: logger.debug('Sending location') bot.send_location(chat_id, **vars(precise_location)) else: logger.debug('Nothing found') bot.send_message(chat_id, text='Ничего не нашли :(') else: welcome(message)
def main(message): photo_1 = open('static/photo1.jpg', 'rb') photo_2 = open('static/photo2.jpg', 'rb') if message.text == 'Сыграть в игру?': msg = bot.send_message( message.chat.id, "Введите число от 1 до 6. Если вы угадали число, которое я загадал. Я отправлю Вам исходный код бота (.py)" ) text = message.text bot.register_next_step_handler(msg, game) ####### if message.text == 'Связаться' or message.text == '/contacts': bot.send_message(message.chat.id, "Каким способом Вы хотели бы связаться?", reply_markup=markup3) elif message.text == 'VK' or message.text == '/vk': bot.send_message(message.chat.id, "<b>https://vk.com/vsetvoidruziya</b>", parse_mode='html') elif message.text == 'Telegram' or message.text == '/telegram': bot.send_message(message.chat.id, "<b>@artemminchenkov</b>", parse_mode='html') elif message.text == 'Email' or message.text == '/email': bot.send_message(message.chat.id, "<b>[email protected]</b>", parse_mode='html') elif message.text == "В начало": bot.send_message(message.chat.id, "Идём в начало...🤔", reply_markup=markup) ####### if message.text == 'Обо мне' or message.text == '/about': bot.send_message(message.chat.id, "Что Вас интересует?", reply_markup=markup2) elif message.text == 'Проекты' or message.text == '/projects': bot.send_message( message.chat.id, "https://github.com/Artemqas - здесь я храню свои исходники", reply_markup=markup2) elif message.text == 'Фотографии' or message.text == '/photo': bot.send_media_group( message.from_user.id, [InputMediaPhoto(photo_1), InputMediaPhoto(photo_2)]) #bot.send_photo(message.chat.id, photo_1, reply_markup = markup2) #bot.send_photo(message.chat.id, photo_2, reply_markup = markup2) elif message.text == 'Резюме' or message.text == '/CV': bot.send_message(message.chat.id, cv) bot.send_message(message.chat.id, about, reply_markup=markup2)
def get_chord(chord, caption): """Parse particular chord images for guitar and ukulele""" return [ InputMediaPhoto( media=os.environ.get('UCHORDS_URL') + 'images/guitar/' + chord + '.png', caption='Аккорд {} на гитаре'.format(caption) ), InputMediaPhoto( media=os.environ.get('UCHORDS_URL') + 'images/' + chord + '.png', caption='Аккорд {} на укулеле'.format(caption) ) ]
def posting_to_channel(channel_id: str, caption: str, *files) -> None: with ExitStack() as stack: pics = [stack.enter_context(open(fp, 'rb')) for fp in files if fp is not None] if not pics: logging.warning('Нет картинок для публикации') return media = [] for i in range(len(pics)): media.append(InputMediaPhoto(pics[i], caption) if i == 0 else InputMediaPhoto(pics[i])) # теперь можно и без прокси safety_send_group(channel_id, media, proxy=False) return
def posting_to_channel(caption, *files, **kwargs): channel_id = CHANNEL_ID if kwargs.get( 'channel_id') is None else kwargs['channel_id'] with ExitStack() as stack: pics = [stack.enter_context(open(fp, 'rb')) for fp in files] media = [] for i in range(len(pics)): media.append( InputMediaPhoto(pics[i], caption) if i == 0 else InputMediaPhoto(pics[i])) working_proxy = check_proxy() safety_send_group(channel_id, media, working_proxy) return
def send_images(message: Message, day, text): weather_types = [['t', 'Температура повітря'], ['gust', 'Пориви вітру'], ['h', 'Вологість повітря'], ['o', 'Опади'], ['c', 'Хмарність']] path = str(message.chat.id) + '_' + str(message.id) try: os.mkdir(path) except OSError: print("Creation of the directory %s failed" % path) else: print("Successfully created the directory %s " % path) day = day bot.send_message(message.chat.id, text, parse_mode='markdown') for type in weather_types: media = [] pictures_to_send = [] download_image.download_images_of_day(day, weather_type=type[0], path=path) for i in range(4): try: tmp_pic = open(path + '/' + str(i) + ".png", "rb") pictures_to_send.append(tmp_pic) if i == 0: media.append( InputMediaPhoto(pictures_to_send[i], caption=type[1])) else: media.append(InputMediaPhoto(pictures_to_send[i])) except: print(str(i) + ".png not found for adding to album ") bot.send_media_group(message.chat.id, media) for image in pictures_to_send: image.close() delete_image.removing_image(path) try: os.rmdir(path) except OSError: print("Deletion of the directory %s failed" % path) else: print("Successfully deleted the directory %s" % path) print('Done sending')
def _send_article_images( self, chat_id: Union[str, int], article_id: str, images_group: list[InputMediaPhoto], forward: bool, forward_images_message: Union[None, list] = None) -> Union[list, None]: try: if not forward: logger.debug('Bot: User {0} - {1} - Try to send photos'.format( str(chat_id), article_id)) message_to_forward = self.bot.send_media_group( chat_id, images_group) logger.debug('Bot: User {0} - {1} - Photos sented'.format( str(chat_id), article_id)) return message_to_forward else: logger.debug( 'Bot: User {0} - {1} - Try to forward photos'.format( str(chat_id), article_id)) self.bot.send_media_group(chat_id, [ InputMediaPhoto(image.photo[0].file_id) for image in forward_images_message ]) logger.debug('Bot: User {0} - {1} - Photos forwarded'.format( str(chat_id), article_id)) return None except Exception as error: logger.exception(error)
def send_post(self, destination): try: # Отправляем текст, нарезая при необходимости 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.gif_links: my_bot.send_document(destination, url) if len(self.image_links) > 0: my_bot.send_media_group( destination, [InputMediaPhoto(url) for url in self.image_links]) if len(self.video_links) > 0: my_bot.send_media_group( destination, [InputMediaVideo(url) for url in self.video_links]) for url in self.audio_links: my_bot.send_audio(destination, url) except apihelper.ApiException: action_log("VK Error: api exception")
def send(self, telegram, chat_id): print(f"[Sending]: {self.caption}") if "/gallery/" in self.post.url: gallery = [] for media in self.post.media_metadata.items(): url = media[1]["p"][0]["u"] url = url.split("?")[0].replace("preview", "i") gallery.append(InputMediaPhoto(media=url)) telegram.send_media_group(chat_id, media=gallery) telegram.send_message(chat_id, text=self.caption) elif self.type == "image": telegram.send_photo( chat_id, photo=self.url, caption=self.caption, ) elif self.type == "video": telegram.send_video( chat_id, data=self.url, caption=self.caption, video=self.url, ) else: telegram.send_message(chat_id, text=self.caption)
def stat_gatherer(message): conn = sqlite3.connect('health_data.db') cur = conn.cursor() cur.execute("SELECT * FROM health_monitor;") data = cur.fetchall() health_stat_array = np.array(data) health_stat_array = np.delete(health_stat_array,[0,1], axis = 0) # удаляю первые две строчки вне указанного временноего диапазона, они почему-то фантомно появлялись всегда pulse = np.asarray(health_stat_array[:,1]) blood_pressure = np.array(health_stat_array[:,2]) saturation = np.array(health_stat_array[:,3]) dates=[datetime.datetime.fromtimestamp(ts) for ts in np.asarray(health_stat_array[:,4])] plotter(pulse,dates,"pulse") plotter(blood_pressure,dates,"blood_pressure") plotter(saturation,dates,"saturation") bot.send_media_group(message.from_user.id,[InputMediaPhoto(open("pulse.png","rb"),caption="Время отчета: {}".format(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S"))), InputMediaPhoto(open("blood_pressure.png","rb")), InputMediaPhoto(open("saturation.png","rb"))])
def update_camera(call): message = call.message camera_num = int(call.data.replace('camera_', '')) with open(CameraView(camera_num).get_image(), 'rb') as img: my_bot.edit_message_media(chat_id=message.chat.id, message_id=message.message_id, media=InputMediaPhoto(img, caption=f'Камера #{camera_num}'), reply_markup=camera_keyboard(camera_num)) my_bot.answer_callback_query(callback_query_id=call.id, show_alert=False, text='✅ Обновлено')
def get_chords(instrument, chords): """Parse chords images for current song""" media_group = [] add = 'guitar/' if instrument['name'] == 'guitar' else '' for chord in list(chords['list'])[:10]: url = os.environ.get('UCHORDS_URL') + 'images/' + add + chord + '.png' media_group.append(InputMediaPhoto(media=url)) return media_group
def pictures(message): global photos if message.media_group_id: bot.send_message(message.chat.id, 'Фотографии необходимо отправлять по одной!') else: photo = InputMediaPhoto(media=message.photo[-1].file_id) photos.append(photo) if len(photos) == 1: print(message) try: application['Отправитель'] = '@' + message.from_user.username except TypeError as e: application['Отправитель'] = f'tg://user?id={message.from_user.id}' application_text = '' for i in application.keys(): application_text = application_text + f'*{i}*: {application[i]}\n' photos.pop(0) print('массив после удаления', photos) photo = InputMediaPhoto(media=message.photo[-1].file_id, caption=application_text, parse_mode='Markdown') photos.append(photo) print('массив после Добавления в условии', photos) keyboard = telebot.types.InlineKeyboardMarkup() keyboard.add( telebot.types.InlineKeyboardButton(text='Добавить доп. фото', callback_data='more_photo') ) keyboard.add( telebot.types.InlineKeyboardButton(text='Завершить отправку фото', callback_data='end_photo') ) bot.send_message(message.chat.id, 'Добавить дополнительные фото?', reply_markup=keyboard) else: print('массив после Добавления не в условии', photos) keyboard = telebot.types.InlineKeyboardMarkup() keyboard.add( telebot.types.InlineKeyboardButton(text='Добавить доп. фото', callback_data='more_photo') ) keyboard.add( telebot.types.InlineKeyboardButton(text='Завершить отправку фото', callback_data='end_photo') ) bot.send_message(message.chat.id, 'Добавить дополнитлеьные фото?', reply_markup=keyboard)
def get_quality(post=None): urls = [] if not post: return urls for attachment in post['attachments']: if attachment['type'] != 'photo': continue max_size_url = max(attachment['photo']['sizes'], key=itemgetter('height'))['url'] urls.append(InputMediaPhoto(max_size_url)) return urls
def send_news(index: int, chat_id: str) -> None: global daily_news_msg, daily_news_data keyboard = InlineKeyboardMarkup() keyboard.add( InlineKeyboardButton( text="⬅️️", callback_data=f"daily_move_to {index - 1 if index > 0 else 'pass'}" ), InlineKeyboardButton( text="➡️", callback_data=f"daily_move_to " f"{index + 1 if index < len(daily_news_data[chat_id]) - 1 else 'pass'}" )) if daily_news_data[chat_id][index]['urlToImage'] is None or daily_news_data[chat_id][index]['urlToImage'] == '' \ or daily_news_data[chat_id][index]['description'] is None: daily_news_data[chat_id].pop(index) send_news(index, chat_id) return try: if requests.get(daily_news_data[chat_id][index]["url"]).ok: keyboard.add( InlineKeyboardButton( 'Читать', url=daily_news_data[chat_id][index]["url"])) except (requests.exceptions.ConnectionError, requests.exceptions.MissingSchema) as ex: log(f'Error in news url\n{ex}', 'error') try: if requests.get(daily_news_data[chat_id][index]['urlToImage']).ok: req = request.Request( daily_news_data[chat_id][index]['urlToImage'], method='HEAD') f = request.urlopen(req) if f.headers['Content-Length'] is not None: if int(f.headers['Content-Length']) > 5242880: raise error.URLError except (requests.exceptions.ConnectionError, requests.exceptions.MissingSchema, error.URLError, UnicodeEncodeError): daily_news_data[chat_id].pop(index) send_news(index, chat_id) return except IndexError as ex: log(f'Index Error in daily news\n{ex}', 'warning') bot.edit_message_media( chat_id=chat_id, message_id=daily_news_msg[chat_id].message_id, media=InputMediaPhoto( daily_news_data[chat_id][index]['urlToImage'], caption= f"<b>{clear_link(daily_news_data[chat_id][index]['title'])}</b>" f"\n\n{clear_link(daily_news_data[chat_id][index]['description'])}" f"\n\n<i>{clear_date(daily_news_data[chat_id][index]['publishedAt'])}</i>" f" <b>{index + 1}/{len(daily_news_data[chat_id])}</b>стр.", parse_mode='HTML'), reply_markup=keyboard)
def run_carousel_template(call, step): user_id = call.message.chat.id try: carousel_img = bot.user_carousel_img(user_id, step) if carousel_img is not None: bot.edit_message_media(chat_id=user_id, message_id=call.message.message_id, media=InputMediaPhoto(carousel_img), reply_markup=keyboard_carousel()) bot.answer_callback_query(callback_query_id=call.id, show_alert=False) else: bot.send_message(user_id, MsgTemplate.carousel_error(success=False)) except Exception: bot.send_message(user_id, MsgTemplate.carousel_error(exception_occurred=True))
def get_info_for_thread(message, desk, thread_num): # переменные треда api = api2ch.DvachApi(desk) thread = api.get_thread(thread_num) text_of_OP = html2text.html2text(thread[0].comment) len_thread = "Всего " + str(len(thread)) + " постов" #-------------------- # генерация текста о треде response_text = "\n" + \ thread[0].subject + \ "\n\n" + \ len_thread + \ "\n\n" + \ text_of_OP[:900] pic = [] file_url = "https://2ch.hk" + str(thread[0].files[0].path) pic.append(file_url) media = [InputMediaPhoto(pic[0], caption=response_text)] for i in range(1, len(thread[0].files)): file_url = "https://2ch.hk" + str(thread[0].files[i].path) pic.append(file_url) media.append(InputMediaPhoto(pic[i])) bot.send_media_group(message.chat.id, media) keyboard = types.InlineKeyboardMarkup() #наша клавиатура key_yes = types.InlineKeyboardButton(text='Да', callback_data='yes') #кнопка «Да» keyboard.add(key_yes) #добавляем кнопку в клавиатуру key_no = types.InlineKeyboardButton(text='Нет', callback_data='no') keyboard.add(key_no) bot.send_message(message.chat.id, "Что делать будем?", reply_markup=keyboard)
def send_to_tg(context: GroupContext, group_id: int): group_card = context.group_card nickname = context.nickname msg_prefix = f"[{group_card}({nickname})]:" image_re = re.compile(r"\[CQ:image,file=(.*?),url=(.*?)]") image_urls = list(map(lambda a: a[1], re.findall(image_re, context.message))) text = re.sub(image_re, lambda a: " ", context.message) msg = f"{msg_prefix} {text}" if image_urls: medias = [InputMediaPhoto(url) for url in image_urls] medias[0].caption = msg # 插入消息内容 current_app.telegram_bot.send_media_group(group_id, medias) else: current_app.telegram_bot.send_message(group_id, msg)
def print_one_post(post, bot, query): image = post.images.all() image = PostImage.objects.filter(post=post) img_list = [] listToStr = ',\n '.join([str(elem) for elem in post.link_list]) for i in image: img_list.append(str(i.images)) media_group = list() for number, url in enumerate(img_list): if number == 1: media_group.append(InputMediaPhoto(media=url)) else: media_group.append(InputMediaPhoto(media=url)) bot.send_media_group(query.message.chat_id, media=media_group) bot.send_message( chat_id=query.message.chat_id, text= f"Название : {post.title}\nОписание : {post.description}\nКонтакты: {post.phone} \nМы в соц.сетях : {listToStr}" )
def chanel_photo_handler(msg): info = db.get_ch(ch_id = msg.chat.id) if not check_ch(info): return file = download_file(msg.photo[-1].file_id) if info.type_mark == 'text': mark = None else: mark = download_file(info.photo_id) photo = editor.edit_photo(info, file, mark) edit_media(msg, InputMediaPhoto(photo.getvalue(), caption = msg.html_caption, parse_mode = 'html'), info) db.new_edit_post(info.id, info.user_id)
def start_message(message): randname = random.randint(0, len(creators) - 1) randother = random.randint(0, len(url[randname]) - 1) pic1 = url[randname][randother] str1 = str(creators[randname]) + '. ' + str( description[randname][randother]) randname = random.randint(0, len(creators) - 1) randother = random.randint(0, len(url[randname]) - 1) pic2 = url[randname][randother] str2 = str(creators[randname]) + '. ' + str( description[randname][randother]) randname = random.randint(0, len(creators) - 1) randother = random.randint(0, len(url[randname]) - 1) pic3 = url[randname][randother] str3 = str(creators[randname]) + '. ' + str( description[randname][randother]) randname = random.randint(0, len(creators) - 1) randother = random.randint(0, len(url[randname]) - 1) pic4 = url[randname][randother] str4 = str(creators[randname]) + '. ' + str( description[randname][randother]) randname = random.randint(0, len(creators) - 1) randother = random.randint(0, len(url[randname]) - 1) pic5 = url[randname][randother] str5 = str(creators[randname]) + '. ' + str( description[randname][randother]) media = [ InputMediaPhoto(pic1, caption='1. ' + str1 + '\n' + '2. ' + str2 + '\n' + '3. ' + str3 + '\n' + '4. ' + str4 + '\n' + '5. ' + str5), InputMediaPhoto(pic2), InputMediaPhoto(pic3), InputMediaPhoto(pic4), InputMediaPhoto(pic5) ] bot.send_media_group(message.chat.id, media)
def send_related(message): bool_ban = SendTrackMessage(message, 'related') if bool_ban: bot.reply_to(message, '你/频道/群组 被BAN了, 请私聊bot确认是否为个人被ban') return 0 try: split_list = message.text.split(' ') if len(split_list) > 3 or len(split_list) < 2: bot.send_message(message.chat.id, '満身創痍|使用范例: /related 43369925 5') return -1 elif len(split_list) == 3: origin_id = split_list[1] num = split_list[2] elif len(split_list) == 2: origin_id = split_list[1] num = 5 int(origin_id) num = int(num) if num <= 0: bot.send_message(message.chat.id, '満身創痍|使用范例: /related 43369925 5') else: api = AppPixivAPI() api.login("your username", "pswe") id_list = PixivRelated(origin_id, num, api) if id_list == []: bot.send_message( message.chat.id, '该图片不存在或没有相关图片|Picture does not exist or has no related illustrations' ) elif len(id_list) < 6: for i in id_list: file, title, tags = PixivDownload(i, api) caption = 'url : pixiv.net/i/' + str( i) + '\n' + 'title : ' + title + '\n' + 'tags : ' for tag in tags: if len(caption) + len(tag) < 193: caption = caption + tag + ' ' bot.send_photo(message.chat.id, file, caption) else: file_list = [] for i in id_list: temp_file, temp1, temp2 = PixivDownload(i, api) file_list.append(InputMediaPhoto(temp_file)) bot.send_media_group(message.chat.id, file_list) except: bot.send_message(message.chat.id, '満身創痍|使用范例: /related 43369925 5')