Code Monkey home page Code Monkey logo

telegram-news's Introduction

Telegram-news
Telegram-news

Python package for automatically fetching and pushing news by Telegram.

PyPI PyPI - Python Version License PyPI - Downloads

Build Status Codacy Badge Last commit https://t.me/eswzy

Introduction

This is a easy-to-learn, flexible and standardized message fetching and pushing framework, especially for Telegram and Telegram Bot.

The target news source can be HTML page, JSON and XML. We also provide customized process for unknown data format.

Push the latest news to your channel or group once it happens!

Install

$ pip install telegram-news

Or, you can install by cloning this repository:

$ git clone https://github.com/ESWZY/telegram-news.git
$ cd telegram-news
$ python setup.py install

Prepare

It does not need much so that you can run your code anywhere.

First, ask @BotFather for a bot and bot token. After that, create a public channel or group, and remember chat id you just named. Do not forget to invite your bot into your channel or group and make it an admin.

You also need a SQL database. Any SQL database is OK. Especially, I recommend PostgreSQL.

Quick deploy on Heroku

Click ๐Ÿ‘‡ button to deploy an example for free. Python environment and PostgreSQL database have been prepared.

Deploy

After deployment, start the worker in "Resources" tab, and then you can see the effect in your channel/group, which contains both SCMP news and Wiki news at same time.

Also, you can have a look at the quick deployment source code of this project in ESWZY/telegram-news-getting-started.

Usage

Those are 3 examples for you to understand how to use the framework.

Basic Example

import os
from sqlalchemy import create_engine
from sqlalchemy.orm import Session

from telegram_news.template import InfoExtractor, NewsPostman

# Three required fields:
# Your bot token obtained from @BotFather
bot_token = os.getenv("TOKEN")
# Add your bots into a channel as an administrator
channel = os.getenv("CHANNEL")
# Your database to store old messages.
DATABASE_URL = os.getenv("DATABASE_URL")

# Create a database session
engine = create_engine(DATABASE_URL)
db = Session(bind=engine.connect())

# The news source
url = "https://en.wikinews.org/wiki/Main_Page"
tag = "Wiki News"
table_name = "wikinews"

# Info extractor to process data format
ie = InfoExtractor()

# Select select element by CSS-based selector
ie.set_list_selector('#MainPage_latest_news_text > ul > li')
ie.set_title_selector('#firstHeading')
ie.set_paragraph_selector('#mw-content-text > div > p:not(p:nth-child(1))')
ie.set_time_selector('#mw-content-text > div > p:nth-child(1) > strong')
ie.set_source_selector('span.sourceTemplate')

# Set a max length for post, Max is 4096
ie.max_post_length = 2000

# News postman to manage sending affair
np = NewsPostman(listURLs=[url, ], sendList=[channel, ], db=db, tag=tag)
np.set_bot_token(bot_token)
np.set_extractor(ie)
np.set_table_name(table_name)

# Start to work!
np.poll()

Typical results:

Demo 1 Demo 2

Advanced Example

import os
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from telegram_news.template import InfoExtractor, NewsPostman
bot_token = os.getenv("TOKEN")
channel = os.getenv("CHANNEL")
DATABASE_URL = os.getenv("DATABASE_URL")
engine = create_engine(DATABASE_URL)
db = Session(bind=engine.connect())

# Above code is as same as the basic example, you can reuse those code directly

url_2 = "https://www.cnbeta.com/"
tag_2 = "cnBeta"
table_name_2 = "cnbetanews"

ie_2 = InfoExtractor()
ie_2.set_list_selector('.items-area > div > dl > dt > a')
ie_2.set_title_selector('header > h1')

# Select many target at same time    
ie_2.set_paragraph_selector('div.cnbeta-article-body > div.article-summary > p, '  # Summary only
                            'div.cnbeta-article-body > div.article-content > p')   # Content only
ie_2.set_time_selector('header > div > span:nth-child(1)')
ie_2.set_source_selector('header > div > span.source')

# Select image to display, then the max length is down to 1024
ie_2.set_image_selector('div.cnbeta-article-body > div.article-summary > p img, '  # From summary only
                        'div.cnbeta-article-body > div.article-content > p img')   # From content only
ie_2.max_post_length = 1000

np_2 = NewsPostman(listURLs=[url_2, ], sendList=[channel], tag=tag_2, db=db)
np_2.set_extractor(ie_2)
np_2.set_table_name(table_name_2)
np_2.poll()

Typical results:

Demo 3 Demo 4

Advanced Example for JSON and XML

The handle for JSON and XML are quite similar. You can convert XML to JSON by function telegram_news.utils.xml_to_json, and use NewsPostmanJSON and InfoExtractorJSON. Or, you can use NewsPostmanXML and InfoExtractorXML directly.

You should use key list to recursively route to the information you want.

import hashlib
import json
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from telegram_news.template import InfoExtractorJSON, NewsPostmanJSON
from telegram_news.utils import xml_to_json
bot_token = os.getenv("TOKEN")
channel = os.getenv("CHANNEL")
DATABASE_URL = os.getenv("DATABASE_URL")
engine = create_engine(DATABASE_URL)
db = Session(bind=engine.connect())

url_3 = "https://www.scmp.com/rss/91/feed"
tag_3 = "SCMP"
table_name_3 = "scmpnews"

ie_3 = InfoExtractorJSON()

# Pre-process the XML string, convert to JSON string
def list_pre_process(text):
    text = json.loads(xml_to_json(text))
    return json.dumps(text)
ie_3.set_list_pre_process_policy(list_pre_process)

# Route by key list
ie_3.set_list_router(['rss', 'channel', 'item'])
ie_3.set_link_router(['link'])
ie_3.set_title_router(['title'])
ie_3.set_paragraphs_router(['description'])
ie_3.set_time_router(['pubDate'])
ie_3.set_source_router(['author'])
ie_3.set_image_router(['media:thumbnail', '@url'])

# Customize ID for news item
def id_policy(link):
    return hashlib.md5(link.encode("utf-8")).hexdigest()
ie_3.set_id_policy(id_policy)

np_3 = NewsPostmanJSON(listURLs=[url_3], sendList=[channel], db=db, tag=tag_3)
np_3.set_extractor(ie_3)
np_3.set_table_name(table_name_3)
np_3.poll()

Typical results:

Demo 5 Demo 6

Parallel Program

If you use the same database and send to the same channel, you can simply joint each part of code block, and call poll() function simultaneously.

An example you can find in our Heroku deploy template repo:

https://github.com/ESWZY/telegram-news-getting-started/blob/master/main.py

Example Channel

A Telegram channel of basic example for English Wikinews: @wikinews_en (in English)

A Telegram channel for realtime earthquake warning powered by Telegram-news: @earthquake_alert (in Chinese)

TODO

  • HTML item list
  • JSON item list
  • XML item list
  • Send Image
  • Send Video
  • Send media group
  • Send file
  • Send audio
  • File sending retry
  • CC as e-mail
  • Webhook
  • Update message by message ID
  • Document
  • GUI

Feedback

Feel free to contact with me if you have any question. Also welcome any contribute.

If you build a channel by this, don't forget to share that good news with us!

License

Licensed under the MIT License.

telegram-news's People

Contributors

dependabot[bot] avatar eswzy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

telegram-news's Issues

sqlalchemy.exc.InvalidRequestError: This session is in 'prepared' state; no further SQL can be emitted within this transaction.

When there are high concurrent requests to datadase with read and write statements, the following exception usually raises.

Traceback (most recent call last):
  File "\telegram-news\telegram_news\template\common.py", line 685, in _post
    self._insert_one_item(news_id)
  File "\telegram-news\telegram_news\template\common.py", line 589, in _insert_one_item
    self._db.execute(query, {"news_id": news_id})
  File "C:\Python\lib\site-packages\sqlalchemy\orm\session.py", line 1277, in execute
    return self._connection_for_bind(bind, close_with_result=True).execute(
  File "C:\Python\lib\site-packages\sqlalchemy\orm\session.py", line 1138, in _connection_for_bind
    return self.transaction._connection_for_bind(
  File "C:\Python\lib\site-packages\sqlalchemy\orm\session.py", line 408, in _connection_for_bind
    self._assert_active()
  File "C:\Python\lib\site-packages\sqlalchemy\orm\session.py", line 281, in _assert_active
    raise sa_exc.InvalidRequestError(
sqlalchemy.exc.InvalidRequestError: This session is in 'prepared' state; no further SQL can be emitted within this transaction.

That may because we (have to) share one database session for many threads. What should I do to avoid it.

Maybe it is not a fatal error, because nothing happened after that exception. Anyway, it's not a good news.

Set all old news item as posted.

When there are too many messages waiting to be posted (e.g. deploy with a new database), it will reach the "Too Many Requests" error. One way to avoid it is to set all old news as posted, and just post news messages from now on.

Job queue for global entities

Need a job queue to control request rate globally. Otherwise, the API will deny the request:

{
	"ok": false,
	"error_code": 429,
	"description": "Too Many Requests: retry after 33",
	"parameters": {
		"retry_after": 33
	}
}

Plain text list handler

Need a new way to just scan a list cyclically to extract info from the list item and not need to go into other webpage.

For example, i just want to extract the title, time and summary from the list below.

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.