def telegraph_lyrics(tittle, artist): telegraph = Telegraph() telegraph.create_account(short_name=Config.TELEGRAPH_SHORT_NAME) GENIUS = Config.GENIUS_API_TOKEN symbol = "❌" if GENIUS is None: result = "Set <b>GENIUS_API_TOKEN</b> in heroku vars for functioning of this command.<br><br><b>Check out this <a href = https://telegra.ph/How-to-get-Genius-API-Token-04-26>Tutorial</a></b>" else: genius = lyricsgenius.Genius(GENIUS) try: songs = genius.search_song(tittle, artist) content = songs.lyrics content = content.replace("\n", "<br>") result = f"<h3>{tittle}</h3><br><b>by {artist}</b><br><br>{content}" symbol = "📜" except (TypeError, AttributeError): result = "<b>Lyrics Not found!</b>" symbol = "❌" try: response = telegraph.create_page( "Lyrics", html_content=result, author_name="CatUserbot", author_url="https://t.me/catuserbot17", ) except Exception as e: symbol = "❌" response = telegraph.create_page( "Lyrics", html_content=str(e), author_name="CatUserbot", author_url="https://t.me/catuserbot17", ) return response["url"], symbol
def create_vacancy_telegraph_page(vacancy: Vacancy, telegraph_account: Telegraph): title = vacancy.name parsed_description = vacancy.description.replace("\n", "<br>") html_content = ( f"<b>Категорія</b>: {vacancy.tag}<br>" f"<b>Досвід</b>: {vacancy.experience}<br>" f"<b>Зарплата</b>: {vacancy.salary}<br>" f"<b>Робочий день</b>: {vacancy.employment_type}<br>" f"<h3>Опис</h3>{parsed_description}<br>" ) author_name = telegraph_account.get_account_info()["author_name"] author_url = telegraph_account.get_account_info()["author_url"] try: response = telegraph_account.create_page( title=title, html_content=html_content, author_name=author_name, author_url=author_url, ) vacancy.telegraph_link_token = response["path"] vacancy.save() except Exception as e: print(e)
def handle(self, *args, **options): news = RSSNews(RSS_Links) telegraph = Telegraph(access_token=os.getenv('TELEGRAPH_ACCESS_TOKEN')) if news.urls: for url, date in news.urls.items(): article = NewsPlease.from_url(url) a = Article(author=', '.join(article.authors) or 'Anonymous', title=article.title, short_text=article.description, content=article.maintext, date=date, source_link=url, img=article.image_url) a.save() response = telegraph.create_page(title=a.title, html_content=a.content) TelegraphArticle(title=a.title, link=response['url']).save() bot.send_telegraph_msg(response['url']) self.stdout.write(self.style.SUCCESS('Success'))
def test_flow(self): telegraph = Telegraph() response = telegraph.create_account( short_name='python telegraph', author_name='Python Telegraph API wrapper', author_url='https://github.com/python273/telegraph') self.assertTrue('access_token' in response) self.assertTrue('auth_url' in response) response = telegraph.get_account_info() self.assertEqual(response['short_name'], 'python telegraph') response = telegraph.edit_account_info( short_name='Python Telegraph Wrapper') self.assertEqual(response['short_name'], 'Python Telegraph Wrapper') response = telegraph.create_page('Python Telegraph API wrapper', html_content='<p>Hello, world!</p>') telegraph.edit_page(response['path'], 'Python Telegraph API Wrapper', html_content=POST_HTML_CONTENT) response = telegraph.get_views(response['path']) self.assertTrue('views' in response) response = telegraph.get_page_list() self.assertTrue(response['total_count'] > 0) response = telegraph.revoke_access_token() self.assertTrue('access_token' in response) self.assertTrue('auth_url' in response)
def sendNewChapter(message): global bot html = '' link = str(message.text) link = link.replace('/get ', '') my_request = urllib.request.Request(link) my_request.add_header( 'User-Agent', "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0)\Gecko/20100101 Firefox/24.0" ) page = urllib.request.urlopen(my_request) text = page.read().decode(encoding="UTF-8") doc = lxml.html.document_fromstring(str(text)) for element in doc.xpath("/html/body/div[6]/script[1]"): if element.text.find("rm_h.init") != -1: script_text = element.text script_line = script_text.split("rm_h.init")[1] script_line = script_line[3:-17] script_line = script_line[:-1].replace('[', '').split('],') links = [] for line in script_line: el = line.replace('"', r"'").replace("'", '') el = el.split(',') lnk = el[1] + el[0] + el[2] lnk = lnk.replace('https://h23.mangas.rocks/manga/', '') links.append(lnk) telegraph = Telegraph(telegraph_token) for i in links: html = html + '<img src="' + i + '"/>' response = telegraph.create_page('Manga', html_content=html) bot.send_message(message.from_user.id, 'https://telegra.ph/{}'.format(response['path']))
def create_telegraph(products: List[Product], period) -> str: telegraph = Telegraph() telegraph.create_account(short_name="Stasher") html_content: str = "" total: float = 0 for index, product in enumerate(products): location = product.location if "{" in product.location and "}" in product.location: _location = construct_location_link( location=json.loads(product.location)) location = f"<a href='{_location}'>Link to location image</a>" html_content += (f"<p>№ {index + 1}</p>" f"<p>Name: {product.name}</p>" f"<p>Price: {round(product.price, 2)}$</p>" f"<p>Date: {product.date} </p>" f"<p>Location: {location}</p><br><br>") total += product.price html_content += "<hr>" html_content += f"<p style='text-align: center'>Total costs: {round(total, 2)}$</p>" page = telegraph.create_page( title="All costs" if period == "all" else f"1 {period}", html_content=html_content, ) return page["url"]
def telegraph_lyrics(tittle, artist): telegraph = Telegraph() telegraph.create_account(short_name=Config.TELEGRAPH_SHORT_NAME) GENIUS = Config.GENIUS_API_TOKEN if GENIUS is None: result = ( "Set <b>GENIUS_API_TOKEN</b> in heroku vars for functioning of this command" ) else: genius = lyricsgenius.Genius(GENIUS) try: songs = genius.search_song(tittle, artist) except TypeError: songs = None if songs is None: result = "<b>Lyrics Not found!</b>" content = songs.lyrics content = content.replace("\n", "<br>") result = f"<h3>{tittle}</h3><br><b>by {artist}</b><br><br>{content}" response = telegraph.create_page( "Lyrics", html_content=result, author_name="CatUserbot", author_url="https://t.me/catuserbot17", ) return response["url"]
def generate_article(user_w: User) -> str: """ This function creates a ``Telegra.ph`` article, based on user_w tracking list, so that the article fits doughnut charts for each tracked by user_w user. Parameters ---------- user_w : user.User User model, which tracking list is being processed and shown up in the article. Returns ------- URL for generated bulk ``telegra.ph`` article """ telegraph = Telegraph() page_template_contents = open("./bot/utils/assets/telegraph_page.jinja2").read() page_template = Template(page_template_contents) telegraph.create_account(short_name='Online Informer') page_contents = page_template.render( user_w=user_w, get_image_url=get_doughnut_chart_url, number_of_users_tracking=len(user_w.get_tracking_users()) ) response = telegraph.create_page( f'{user_w.first_name}({user_w.user_id}) Tracking list', html_content=page_contents ) return 'https://telegra.ph/{}'.format(response['path'])
def sent_url_post(data_to_sent): m = template.render(data=data_to_sent) print(m) telegraph = Telegraph() telegraph.create_account(short_name="starava_bot") response = telegraph.create_page('ioiioio data', html_content=m) print(response) return ('https://telegra.ph/{}'.format(response['path']))
def put_telegraph(title, md_text): tele = Telegraph() tele.create_account(short_name='Bot') response = tele.create_page(title=title, html_content=md_text) text_url = 'https://telegra.ph/{}'.format(response['path']) return text_url
def telegraph_submit(message_title, message_content): title = message_title content = message_content telegraph = Telegraph() telegraph.create_account(short_name='FileBot') response = telegraph.create_page(title, html_content=content) posted = 'http://telegra.ph/{}'.format(response['path']) telegram(title, posted)
async def down_load_media_f(client, message): user_id = message.from_user.id print(user_id) mess_age = await message.reply_text("processing...", quote=True) if not os.path.isdir(DOWNLOAD_LOCATION): os.makedirs(DOWNLOAD_LOCATION) if message.reply_to_message is not None: start_t = datetime.now() download_location = "/app/" c_time = time.time() the_real_download_location = await client.download_media( message=message.reply_to_message, file_name=download_location, progress=progress_for_pyrogram, progress_args=("trying to download", mess_age, c_time)) end_t = datetime.now() ms = (end_t - start_t).seconds LOGGER.info(the_real_download_location) sam = os.path.basename(the_real_download_location) extension = os.path.splitext(the_real_download_location)[1] if extension == ".srt" or extension == ".vtt": with open(the_real_download_location) as myfile: head = [next(myfile) for x in range(7)] with open(u_output) as myfile: telegraph = Telegraph() telegraph.create_account(short_name='1337') response = telegraph.create_page('Subtitle Content', html_content="".join([ next(myfile) + "<br>" for x in range(50) ])) file_context = 'https://telegra.ph/{}'.format( response['path']) await mess_age.edit_text( f"<b>OUTPUT:</b>\n\n<code>{the_real_download_location}</code>\n\n<b>First 7 lines of Sub:</b>\n\n<code>{head}</code>\n\nFinished in <u>{ms}</u> seconds", reply_markup=InlineKeyboardMarkup([ [ InlineKeyboardButton('🌿 Subtitle Content 🌿', url=file_context) ], ])) the_real_download_location_g = os.path.basename( the_real_download_location) LOGGER.info(the_real_download_location_g) else: await mess_age.edit_text( f"<b>OUTPUT:</b>\n\n<code>{the_real_download_location}</code>\n\nFinished in <u>{ms}</u> seconds" ) the_real_download_location_g = os.path.basename( the_real_download_location) LOGGER.info(the_real_download_location_g) else: #await asyncio.sleep(4) await mess_age.edit_text( "Reply to a Telegram Media, to save to the server.")
def create_instant_view(url): telegraph = Telegraph(teletoken) title, content = parse_article(url) try: response = telegraph.create_page(title=title, html_content=content) return response['url'] # url of created telegraph page except TelegraphException: # if article is too big print("Oh no, something went wrong.") titles, contents = parse_article(url, too_big=True) response1 = telegraph.create_page(title=titles[0], html_content=contents[0]) response2 = telegraph.create_page(title=titles[1], html_content=contents[1]) # urls of created telegraph pages return [response1['url'], response2['url']]
def write_state(self, title, picture): from telegraph import Telegraph telegraph = Telegraph() telegraph.create_account(short_name='1337') response = telegraph.create_page(str(title), html_content=str(picture)) print('https://telegra.ph/{}'.format(response['path']))
def export_to_telegraph(self, content: str): telegraph = Telegraph(TELEGRAPH_USER_TOKEN) if self.is_changed(): telegraph_response = telegraph.create_page(title=self.title, html_content=content) else: telegraph_response = telegraph.edit_page(path=self.telegraph_path, title=self.title, html_content=content) print(telegraph_response)
def parse_and_post_to_telegraph(title: str, blocks: list, proxies: dict = None) -> str: telegraph = Telegraph() if proxies: telegraph._telegraph.session.proxies = proxies telegraph.create_account(short_name='1337') content = parse_dtf_blocks(blocks) response = telegraph.create_page(title=title, content=content) return f'https://telegra.ph/{response["path"]}'
def drive_list(self, fileName): msg = f'<h4>Search Results for : {fileName}</h4><br><br>' # Create Search Query for API request. Search_fileName = fileName.replace(" ", "' and name contains '") INDEX_ID = 0 for parent_id in DRIVE_ID: query = f"'{parent_id}' in parents and (name contains '{Search_fileName}')" response = self.__service.files().list( supportsTeamDrives=True, includeTeamDriveItems=True, q=query, spaces='drive', pageSize=PAGE_SIZE, fields='files(id, name, mimeType, size)', orderBy='modifiedTime desc').execute() index_url = INDEX_URL[INDEX_ID] INDEX_ID += 1 if response["files"]: for file in response.get('files', []): if file.get( 'mimeType' ) == "application/vnd.google-apps.folder": # Detect Whether Current Entity is a Folder or File. msg += f"📁 <code>{file.get('name')}<br>(folder)</code><br>" \ f"<b><a href='https://drive.google.com/drive/folders/{file.get('id')}'>GDrive Link</a></b>" if index_url is not None: url_path = requests.utils.quote( f'{file.get("name")}') url = f'{index_url}/{url_path}/' msg += f' <b>| <a href="{url}">Index Link</a></b>' else: msg += f"📄 <code>{file.get('name')}<br>({self.get_readable_file_size(file.get('size'))})</code><br>" \ f"<b><a href='https://drive.google.com/uc?id={file.get('id')}&export=download'>GDrive Link</a></b>" if index_url is not None: url_path = requests.utils.quote( f'{file.get("name")}') url = f'{index_url}/{url_path}' msg += f' <b>| <a href="{url}">Index Link</a></b>' msg += '<br><br>' else: None telegraph = Telegraph() telegraph.create_account(short_name='Asta') response = telegraph.create_page(title='GDrive Search Bot', author_name='Adnan Ahmad', author_url='https://t.me/viperadnan', html_content=msg)['path'] msg = f"<b>Search Results For :</b> <code>{fileName}</code>" buttons = button_builder.ButtonMaker() buttons.buildbutton("Open in Telegraph", f"https://telegra.ph/{response}") return msg, InlineKeyboardMarkup(buttons.build_menu(1))
def drive_list(self, fileName): msg = f'<h4>Results : {fileName}</h4><br>@LoaderXbot #ProjektX<br><br>' # Create Search Query for API request. INDEX_ID = 0 for parent_id in DRIVE_ID: query = f"'{parent_id}' in parents and (name contains '{fileName}')" response = self.__service.files().list( supportsTeamDrives=True, includeTeamDriveItems=True, q=query, spaces='drive', pageSize=200, fields='files(id, name, mimeType, size)', orderBy='modifiedTime desc').execute() index_url = INDEX_URL[INDEX_ID] INDEX_ID += 1 msg += f"тОтттттттттттттМ<br><b>Team Drive : {INDEX_ID}</b><br>тОтттттттттттттМ<br>" if response["files"]: for file in response.get('files', []): if file.get( 'mimeType' ) == "application/vnd.google-apps.folder": # Detect Whether Current Entity is a Folder or File. msg += f"т<code>{file.get('name')}<br>(folder№)</code><br>" \ f"<b><a href='https://drive.google.com/drive/folders/{file.get('id')}'>Drive Link</a></b>" if index_url is not None: url_path = requests.utils.quote( f'{file.get("name")}') url = f'{index_url}/{url_path}/' msg += f' <b>| <a href="{url}">Index Link</a></b>' else: msg += f"т<code>{file.get('name')}<br>({self.get_readable_file_size(file.get('size'))})№</code><br>" \ f"<b><a href='https://drive.google.com/uc?id={file.get('id')}&export=download'>Drive Link</a></b>" if index_url is not None: url_path = requests.utils.quote( f'{file.get("name")}') url = f'{index_url}/{url_path}' msg += f' <b>| <a href="{url}">Index Link</a></b>' msg += '<br><br>' else: msg += "т <code>No Results</code><br><br>" telegraph = Telegraph() telegraph.create_account(short_name='Asta') response = telegraph.create_page(title='LoaderX', author_name='svr666', author_url='https://t.me/svr666', html_content=msg)['path'] msg = f"<b>Search Results For {fileName} №</b>" buttons = button_builder.ButtonMaker() buttons.buildbutton("HERE", f"https://telegra.ph/{response}") return msg, InlineKeyboardMarkup(buttons.build_menu(1))
def teleGraph(short_name,page_title,page_contents): # simple function to make a telegraph page telegraphy = Telegraph() telegraphy.create_account(short_name=short_name) response = telegraphy.create_page( page_title, html_content=page_contents ) return response["url"]
def post_telegraph(bot: Bot, update: Update, args: List[str]): short_name = "Created By @MidukkiBot 😬" msg = update.effective_message # type: Optional[Message] telegraph = Telegraph() r = telegraph.create_account(short_name=short_name) auth_url = r["auth_url"] LOGGER.info(auth_url) title_of_page = " ".join(args) page_content = msg.reply_to_message.text page_content = page_content.replace("\n", "<br>") response = telegraph.create_page(title_of_page, html_content=page_content) msg.reply_text("https://telegra.ph/{}".format(response["path"]))
def publish(chapterurl): html = requests.get(chapterurl, headers=headers).text soup = BeautifulSoup(html, "html.parser") title=soup.find("h1").text content=str(soup.find(id="content")).replace("<div id=\"content\">",'').replace('</div>','') telegraph = Telegraph() telegraph.create_account(short_name='novelbot') response = telegraph.create_page( title, html_content =content ) return 'https://telegra.ph/{}'.format(response['path'])
class TelegraphSaver(HighlightingSaver): def __init__(self, title): super().__init__(title) self.title = title self.telegraph = Telegraph() self.telegraph.create_account('telegraph_saver') def save(self, code: str) -> str: if self._highlighter: code = self._highlighter.highlight(code) response = self.telegraph.create_page(self.title, html_content=code) return f"https://telegra.ph/{response['path']}"
def send_telegraph(feed): telegraph = Telegraph(TELEGRAPH_TOKEN) if not feed['content'].strip(): return '' try: ret = telegraph.create_page( feed['title'], html_content=fix_html(feed['content'])) except ParsingException as e: log.warning("url:"+feed['url']+" "+str(e)) return '' except TelegraphException as e: log.warning("url:"+feed['url']+" "+str(e)) return '' return 'https://telegra.ph/{}'.format(ret['path'])
def post_telegraph(update, context): args = context.args short_name = "Created By @MetaButler" msg = update.effective_message # type: Optional[Message] telegraph = Telegraph() r = telegraph.create_account(short_name=short_name) auth_url = r["auth_url"] LOGGER.info(auth_url) title_of_page = " ".join(args) page_content = msg.reply_to_message.text page_content = page_content.replace("\n", "<br>") response = telegraph.create_page( title_of_page, html_content=page_content ) send_message(update.effective_message, "https://telegra.ph/{}".format(response["path"]))
def sauce(update: Update, context: CallbackContext) -> None: """ Fetch the doujin for all the sauces given by user, make telegraph article and send it to user for easy reading :param update: object representing the incoming update. :param context: object containing data about the command call. """ # check if any args were given if not context.args: update.effective_message.reply_text( "Please give some codes to fetch, this cat can't read your mind..." ) return # check if exception for sauce is added in current chat exception = update.effective_chat.id in get_command_exception_chats( "sauce") # iterate over each given sauce and fetch the doujin for digits in context.args: # get basic info title, data, image_tags = get_info(digits) # create telegraph article for the doujin telegraph = Telegraph() telegraph.create_account(short_name='neko-chan-telebot') article_path = telegraph.create_page(title, html_content=image_tags)['path'] # add details to the reply to be sent to the user text_blob = f"<code>{digits}</code>\n<a href='https://telegra.ph/{article_path}'>{title}</a>" for key, value in data.items(): if value: text_blob += f"\n\n<code>{key}</code>\n{value}" # send message if exception: update.message.reply_html(text_blob) else: context.bot.send_message(chat_id=update.effective_user.id, text=text_blob, parse_mode=ParseMode.HTML) # if called from a chat without exception in it, then send him a reminder to check it if not exception and update.effective_chat.type != "private": update.message.reply_markdown( f"[Let's enjoy this together in our private chat...](https://t.me/{escape_markdown(context.bot.username)}" )
def generatePost(content_tuple): """ Create telegraph page Using telegraph API: https://telegra.ph/api """ telegraph = Telegraph() telegraph.create_account(short_name='E-Tasi') html_content = content_tuple[0] title = content_tuple[1] response = telegraph.create_page(title=title, author_name='ruanyf ( 阮一峰 ) 著 E-Tsai 搬运', html_content=html_content) url = 'https://telegra.ph/{}'.format(response['path']) print(Fore.GREEN + url + Fore.WHITE)
async def notepad_telegraph(msg): try: if msg['chat']['type'] == 'supergroup' and msg['text'].split( )[0] == 'notepad': conteudo_html = msg['text'][8:] telegraph = Telegraph() a = telegraph.create_account(short_name='manicomio') response = telegraph.create_page('TCXS Project', html_content=conteudo_html) link_final = 'https://telegra.ph/{}'.format(response['path']) print(f"Usuário criou um site no telegra.ph: {link_final}") await bot.sendMessage( msg['chat']['id'], f"🤖 {msg['from']['first_name']} acabei seu site:{link_final}", reply_to_message_id=msg['message_id']) except Exception as e: pass
def create_telegraph_post(list_of_img, title, text): telegraph = Telegraph() telegraph.create_account(short_name='FB_test') links_to_img = upload.upload_file(list_of_img) img_links = '' for link in links_to_img: temp = f"""<img src={link}>""" img_links += temp html_content = f""" {img_links} {text} """ response = telegraph.create_page(title=title, html_content=html_content) return 'https://telegra.ph/{}'.format(response['path'])
class TestAPI(TestCase): def setUp(self): self.t = Telegraph( 'd676e590b0c6bac0ea58cfcdd350272691ea9fb10b2aeb33edcf68dbb20d') def tearDown(self): self.t.close() def test_get_page(self): page = self.t.get_page('api') self.assertEqual(page.title, 'Telegraph API') def test_create_page(self): page = self.t.create_page(title="Test Page", return_content=True, content=CONTENT) self.assertEqual(page.content, CONTENT)
def create_instant_view(content, title, bot, uid, too_big=False): telegraph = Telegraph(TELEGRAPH_TOKEN) bot.send_chat_action(uid, 'typing') try: response = telegraph.create_page(title=title, html_content=content) return response['url'] # url of created telegraph page except TelegraphException: new_content = "<h".join( content.split('<h')[:-1] ) + "<br></br><aside>Сделано ботом <br></br><a href ='https://telegram.me/WikipediaTelegraphBot?start=from_telegraph'> @WikipediaTelegraphBot</a></aside>" print('too big article') return create_instant_view(make_pretty(new_content), title, bot, uid, too_big=True)