Skip to content

Commit

Permalink
Adicionada opção de Visualização Rápida usando Telegraph
Browse files Browse the repository at this point in the history
  • Loading branch information
GabrielRF committed Sep 7, 2023
1 parent 8baa4dc commit 3aa832e
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 2 deletions.
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ Defina as variáveis na aba `Variables` do repositório:

`TOPIC`: (opcional) ID do tópico em que a mensagem será enviada. Necessário para grupos com a opção de tópicos ativada. [Como obter um ID de um tópico](#id-de-tópico)

`TELEGRAPH_TOKEN`: (opcional) Chave para acesso ao Telegraph. [Como obter uma chave Telegraph](#chave-telegraph)

`HIDE_BUTTON`: (opcional) Caso definida, desabilita o botão no envio, permitindo assim a existência do `Leitura Rápida`.

### Opções de variáveis
Expand Down Expand Up @@ -92,3 +94,34 @@ A ação irá buscar as atualizações a cada hora conforme definido no arquivo
Caso o grupo tenha a opção de tópicos ativada, será necessário indicar em qual tópico a mensagem será enviada. Isto é feito usando-se a variável `TOPIC`. A maneira mais fácil de se obter um ID de um tópico é copiando o link de uma mensagem de um tópico. O ID será o penúltimo número do link.

Exemplo: O link para uma mensagem de um tópico seria `https://t.me/c/987654321/123/4567`. Neste caso, `123` seria o ID do tópico, o número que deveria ser colocado na variável.

## Chave Telegraph

> Atenção: Caso a variável <i>TELEGRAPH_TOKEN</i> esteja definida, o post não terá botão ou imagem, pois ambos não permitiriam a existência da opção "Visualização Rápida".
Para criar sua chave de acesso ao Telegraph e gerar a <i>Visualização Rápida</i> de qualquer site, acesse:

```
https://api.telegra.ph/createAccount?short_name=<SHORT_NAME>&author_name=<AUTHOR_NAME>
```

* `SHORT_NAME`: Uma abreviação de seu nome;

* `AUTHOR_NAME`: Seu nome.

A resposta do site será algo como:

```
{
"ok": true,
"result": {
"short_name": "NOME",
"author_name": "NOME",
"author_url": "",
"access_token": "abcdefghijklmnopqrtuvxz123456789",
"auth_url": "https://edit.telegra.ph/auth/123456789012345678901234567890"
}
}
```

O valor presente em `access_token` é o valor a ser usado na variável `TELEGRAPH_TOKEN`.
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ requests==2.28.0
feedparser==6.0.10
bs4==0.0.1
beautifulsoup4==4.11.1
telegraph==1.4.1
26 changes: 24 additions & 2 deletions rss2telegram.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import os
import re
import telebot
import telegraph
import time
import random
import requests
Expand All @@ -24,6 +25,7 @@ def get_variable(variable):
HIDE_BUTTON = os.environ.get('HIDE_BUTTON', False)
DRYRUN = os.environ.get('DRYRUN')
TOPIC = os.environ.get('TOPIC', False)
TELEGRAPH_TOKEN = os.environ.get('TELEGRAPH_TOKEN', False)

bot = telebot.TeleBot(BOT_TOKEN)

Expand Down Expand Up @@ -63,15 +65,35 @@ def firewall(text):
result = True
return result

def create_telegraph_post(topic):
telegraph_auth = telegraph.Telegraph(
access_token=f'{get_variable("TELEGRAPH_TOKEN")}'
)
response = telegraph_auth.create_page(
f'{topic["title"]}',
html_content=(
f'{topic["summary"]}<br><br>'
+ f'<a href="{topic["link"]}">Ver original ({topic["site_name"]})</a>'
),
author_name=f'{topic["site_name"]}'
)
return response["url"]

def send_message(topic, button):
if DRYRUN == 'failure':
return

MESSAGE_TEMPLATE = os.environ.get(f'MESSAGE_TEMPLATE', False)

if MESSAGE_TEMPLATE:
MESSAGE_TEMPLATE = set_text_vars(MESSAGE_TEMPLATE, topic)
else:
MESSAGE_TEMPLATE = f'<b>{topic["title"]}</b>'

if TELEGRAPH_TOKEN:
iv_link = create_telegraph_post(topic)
MESSAGE_TEMPLATE = f'<a href="{iv_link}">󠀠</a>{MESSAGE_TEMPLATE}'

if not firewall(str(topic)):
print(f'xxx {topic["title"]}')
return
Expand All @@ -82,11 +104,11 @@ def send_message(topic, button):
btn = types.InlineKeyboardButton(f'{button}', url=topic['link'])
btn_link.row(btn)

if HIDE_BUTTON:
if HIDE_BUTTON or TELEGRAPH_TOKEN:
for dest in DESTINATION.split(','):
bot.send_message(dest, MESSAGE_TEMPLATE, parse_mode='HTML', reply_to_message_id=TOPIC)
else:
if topic['photo']:
if topic['photo'] and not TELEGRAPH_TOKEN:
response = requests.get(topic['photo'], headers = {'User-agent': 'Mozilla/5.1'})
open('img', 'wb').write(response.content)
for dest in DESTINATION.split(','):
Expand Down

0 comments on commit 3aa832e

Please sign in to comment.